2

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.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Hasley
  • 79
  • 6
  • 1
    Does this answer your question? [How can I convert a DOM element to a jQuery element?](https://stackoverflow.com/questions/625936/how-can-i-convert-a-dom-element-to-a-jquery-element) – SuperStormer Dec 11 '20 at 18:28

1 Answers1

1

You can pass the element or elements to the jQuery function.

$(qsOutput).attr("alt", "the new alt attribute");
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • This answers my question, thanks. And the link provided by @SuperStormer answered the other part of my question on how to go from jquery back into an HTMLElement. – Hasley Dec 13 '20 at 17:29