Reputation: 99
I am trying to cut back on jQuery usage, but at times I still need to use a method in jQuery.
Is it possible to convert the return of document.querySelector
or document.querySelectorAll
into a jQuery object, or a jQuery selection into an Element or NodeList object that document.querySelector() or document.querySelectorAll() would return?
Re-doing a selection seems more expensive than working with what I already have.
Here is an example with document.querySelector
:
let qsOutput = document.querySelector('#my_id');
//now if I want to use jQuery's .attr (just as an example)
qsOutput.attr("alt", "the new alt attribute"); //.attr() is a jquery function
How would I do this? Do I just have to select again and waste resources of the original capture?
I am NOT asking how to change an attribute in vanilla JavaScript, I am trying to cut back on jQuery usage but still need to use it from time to time, but making a new selection with it, when I already have one through document.querySelector
, seems like a waste. If it is possible, I want to reuse the return of document.querySelector
and just "upgrade" it to jQuery.
Upvotes: 2
Views: 1767
Reputation: 89517
You can pass the element or elements to the jQuery function.
$(qsOutput).attr("alt", "the new alt attribute");
Upvotes: 1