Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent javascript function for .add() in jquery?

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

like image 879
Rishi Raj Avatar asked Mar 02 '26 02:03

Rishi Raj


2 Answers

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.

like image 168
ADyson Avatar answered Mar 04 '26 15:03

ADyson


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

like image 33
charlietfl Avatar answered Mar 04 '26 14:03

charlietfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!