1

I have an example like this:

<div id="President">
  <div id="Congressman">
    <div id="Senator">
      <div id="Major"></div>
    </div>
  </div>
</div>

Is there an easy way in Javascript or jQuery that we can check if the div 'Major' is a child element of all other divs? Thank you.

2
  • 3
    So you have to check if it is a child of them ALL? Commented Feb 13, 2017 at 20:36
  • I think in this case we can have a loop. Commented Feb 13, 2017 at 20:37

4 Answers 4

3

Use javascript node.contains(other node)

var qS = function(v) { return document.querySelector(v); };

console.log(qS('#President').contains(qS('#Major')))
<div id="President">
  <div id="Congressman">
    <div id="Senator">
      <div id="Major"></div>
    </div>
  </div>
</div>


Updated based on comment, combining jQuery and plain javascript

console.log( $('#President')[0].contains( $('#Major')[0] ) )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="President">
  <div id="Congressman">
    <div id="Senator">
      <div id="Major"></div>
    </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

5 Comments

I will try this right now. Thank you for your answer :)
@LanMai Added a sample how to
Thank you very much! Your answer worked! Just a small question: If I use var outer = $('#President') it won't work. Can I use $() in this case?
@LanMai Not like that, as you will mix jQuery with plain javascript ... will add a sample how to
@LanMai Updated, added a 2:nd sample
2

Use has():

console.log($('#President').has('#Major').length > 0)
<script src="https://code.jquery.com/jquery-3.1.1.min.js" 
	integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
	crossorigin="anonymous">
</script>
<div id="President">
  <div id="Congressman">
    <div id="Senator">
      <div id="Major"></div>
    </div>
  </div>
</div>

3 Comments

I will try this right now. Thank you for your answer :)
You mean $('#President').has('#Major')
Thanks for informing. My mistake @blex
2

Is children of all other divs (using jquery):

$('#Major').parents('#Senator,#Congressman,#President').length === 3

1 Comment

This is the simplest and shortest answer that checks that all divs are parents of #Major.
0

This is not the best way to do it but it's a simple one and it works

$('#President').find('#Major').length !== 0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.