Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replicating jQuery's .next('a') with vanila javascript

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.

like image 804
Ilja Avatar asked Nov 11 '15 14:11

Ilja


People also ask

What is replacing jQuery?

JavaScript: Native JavaScript is one of the most common alternatives to jQuery.

What is $( this in JavaScript?

$(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.

What is JS vanilla?

"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.


1 Answers

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>
like image 183
Shomz Avatar answered Nov 20 '22 20:11

Shomz