Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter elements in vanilla Javascript like in jQuery?

For example, in jQuery, if i want all <div> and <p> elements, I do this:

var $x = $("p, div");

And then if i want all the <div> elements in x, then I do this:

var $divs = $x.filter("div");

So how do i do this simple filter thing in vanilla JavaScript?

For example, to select all <div> and <p>, then I can do this:

var x = document.querySelectorAll("div, p");

But vanilla JavaScript doesn't have the filter function like in jQuery, so I can't do this:

var divs = x.filter("div"); // ERROR

Hope someone can help me with this :-)

Thanks in advance.

UPDATE

Some comments/answers have suggested to do something like .tagName == "DIV" to find the divs, however, i want a solution with a string selector like in jQuery.

The reason is because i also want to filter with attributes, classes and even multiple selectors where you put in comma. And the string selector must be dynamic.

That means, i dont know whats in the selector. It could be "div[foo='asd'], .bar" or "#hello, [xx='yy'], p"

So i cant just hardcode the .tagName == "DIV", beacuse i dont know whats in the selector string.

like image 332
Assassinbeast Avatar asked May 29 '18 20:05

Assassinbeast


People also ask

How do you filter an element in JavaScript?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

Can you mix vanilla JavaScript with jQuery?

Yes, any code that you write in jQuery can also be written in vanilla JavaScript. One of the reasons jQuery was developed was to solve browser compatibility issues.

Is there a filter function in JavaScript?

The JavaScript filter array function is used to filter an array based on specified criteria. After filtering it returns an array with the values that pass the filter. The JavaScript filter function iterates over the existing values in an array and returns the values that pass.

What is difference between grep and filter in jQuery?

The grep() method finds an element and the filter() method returns elements matching a specific criteria.


1 Answers

You can use the matches function to check if a CSS selector matches a given element.

var x = document.querySelectorAll("div, p");
var divs = [];

// Iterate through the elements that the first query selector matched
//  (is a paragraph or a div tag)
for (var elem of x) {
    // Check if the given element matches the second query selector
    //  (is a div tag)
    if (elem.matches('div')) {
        divs.push(elem);
    }
}

This code can be written more succinctly (and with more modern code) using:

let x = document.querySelectorAll("div, p");
let divs = Array.from(x).filter(elem => elem.matches("div"));
like image 155
Dave F Avatar answered Oct 20 '22 17:10

Dave F