I'm trying to achieve following in vanila javascript
$('#myElement').next('a').length > 0
At the moment I'm at this stage
document.getElementById('myElement').nextSibling.length > 0
But I need to specifically check if there is an anchor tag <a>
with class .item
after #myDiv
, as there can and cannot be one, and I need to apply specific styling to #myDiv
in each case.
JavaScript: Native JavaScript is one of the most common alternatives to jQuery.
$(this) is a jQuery object and this is a pure DOM Element object. See this example: $(".test"). click(function(){ alert($(this). text()); //and alert(this.
"VanillaJS is a name to refer to using plain JavaScript without any additional libraries like jQuery back in the days. People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries." Or, in our case, without new, fancy frameworks.
You can do something like:
document.getElementById('myElement').nextElementSibling.tagName == 'A'
Make sure you use nextElementSibling
, not nextSibling
in order to be able to check the tag name.
See 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With