Replication jQuery.next ('a') with vanila javascript

I am trying to achieve the following in vanila javascript

$('#myElement').next('a').length > 0 

I'm currently at this stage

 document.getElementById('myElement').nextSibling.length > 0 

But I need to specifically check if the attached <a> tag exists with the .item class after #myDiv , since it may not be one, and I need to apply a specific style to #myDiv in each case.

+8
javascript jquery
source share
1 answer

You can do something like:

 document.getElementById('myElement').nextElementSibling.tagName == 'A' 

Make sure you use nextElementSibling and not nextSibling to check the tag name.

Look here:

 console.log(check('myElement')); console.log(check('almostRightElement')); console.log(check('rightElement')); console.log(check('noSiblings')); function check(id){ var el = document.getElementById(id).nextElementSibling; return !!el && el.tagName == 'A' && el.className == 'item'; /* used !!el just to make the check function always return a boolean it is not necessary as nextElementSibling will return null if no element is found, and since null is falsy, it will break the chain anyway */ } 
 <div> <div id="myElement"></div> <div></div> </div> <div> <div id="almostRightElement"></div> <a></a> </div> <div> <div id="rightElement"></div> <a class="item"></a> </div> <div> <div id="noSiblings"></div> </div> 
+11
source share

All Articles