Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any element in a NodeList has a specific class using ES6

I want to check if any element in a NodeList has a specific class.

For example, with jQuery I just do something like:

//if any .item element has active class, return true
var isActive = $(".item").hasClass("active"); 

Only with Javascript I could do, but with a slightly longer code:

var isActive = false;
var items = Array.from(document.getElementsByClassName("item"));

items.forEach(function(item, index) {
  if(item.className.indexOf('active') > 0) {
	isActive = true;
  }
});

alert(isActive);
<div class="item">1</div>
<div class="item">2</div>
<div class="item active">3</div>
<div class="item">4</div>

How can I do this with ES6? There is a helper for selectors?

Thanks!

like image 611
Adriano Godoy Avatar asked Aug 23 '16 14:08

Adriano Godoy


2 Answers

Array.from(document.getElementsByClassName("item")).some(({classList}) =>
   classList.contains('active'))

is probably the best ES6 can give you, which is essentially the same as your code above.

like image 101
Jakub Hampl Avatar answered Oct 05 '22 06:10

Jakub Hampl


It has nothing to do with ES2015, but you can use document.querySelector() much like the basic jQuery API:

 var isActive = document.querySelector(".item.active") != null;
like image 41
Pointy Avatar answered Oct 05 '22 04:10

Pointy