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.
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.
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.
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.
The grep() method finds an element and the filter() method returns elements matching a specific criteria.
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"));
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