Reputation: 422
For example for the given jquery snippet, what should be the equivalent javascript. An equivalent add method in javascript can be helpful.
$("h1").add("span").add("h2");
As it clearly is mentioned in the jquery docs - .add()
does not add any DOM element. https://api.jquery.com/add/ So using, .appendChild()
does not serve the purpose here
Upvotes: 2
Views: 467
Reputation: 171679
That would create a collection of all <h1>
, <span>
and <h2>
in page
A collection of those same elements using vanilla js would be:
document.querySelectorAll('h1, span, h2')
My guess is you expect add()
to do something different than this but without more details about your use case this would do what is shown in the question
Upvotes: 3
Reputation: 56754
Using the native DOM API only you'd have to do a little more:
let collection = [];
let h1 = document.querySelectorAll("h1")
let span = document.querySelectorAll("span")
let h2 = document.querySelectorAll("h2")
collection.push([...h1]);
collection.push([...span]);
collection.push([...h2]);
console.dir(collection);
<h1>Headline 1</h1>
<p>THis will not end up in the collection (except <span>this</span>)</p>
<h2>Headline 2</h2>
<span>This closes it out.</span>
Upvotes: 2
Reputation: 61859
The documentation at https://api.jquery.com/add says
"Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. ".
This method doesn't perform any DOM operations, it's purely something for use to manipulate a jQuery object. So as far as I can see there would be no direct equivalent - if you don't use jQuery then by definition you can't create or manpiulate a jQuery object.
P.S. You can always examine the jQuery source code for the method to see what it does.
Upvotes: 5