首页 > 解决方案 > 将 document.querySelector 或 document.querySelectorAll 的结果转换为 jquery 对象,反之亦然,无需重新选择?

问题描述

我试图减少 jQuery 的使用,但有时我仍然需要在 jQuery 中使用方法。

是否可以将返回document.querySelectordocument.querySelectorAll转换为 jQuery 对象,或将 jQuery 选择转换为 document.querySelector() 或 document.querySelectorAll() 将返回的 Element 或 NodeList 对象?

重新进行选择似乎比使用我已经拥有的更昂贵。

这是一个例子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

我该怎么做?我是否只需要再次选择并浪费原始捕获的资源?

我不是在问如何更改 vanilla JavaScript 中的属性,我正在尝试减少 jQuery 的使用,但仍需要不时使用它,但是当我已经通过它进行新选择时document.querySelector,似乎浪费。如果可能的话,我想重用它的返回document.querySelector并将其“升级”到 jQuery。

标签: javascriptjquery

解决方案


您可以将一个或多个元素传递给 jQuery 函数。

$(qsOutput).attr("alt", "the new alt attribute");

推荐阅读