如何将 DOM 元素转换为 jQuery 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/625936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:28:41  来源:igfitidea点击:

How can I convert a DOM element to a jQuery element?

jquery

提问by Tanmoy

I am creating an element with document.createElement(). Now how can I pass it to a function that only takes a Jquery object?

我正在使用 document.createElement() 创建一个元素。现在我怎样才能将它传递给一个只接受 Jquery 对象的函数?

$("#id") 

I can not use it, as the element has not been rendered in the page yet.

我无法使用它,因为该元素尚未在页面中呈现。

回答by Marius

var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element

回答by Russ Cam

What about constructing the element using jQuery? e.g.

使用 jQuery 构造元素怎么样?例如

$("<div></div>")

creates a new div element, ready to be added to the page. Can be shortened further to

创建一个新的 div 元素,准备添加到页面中。可以进一步缩短为

$("<div>")

then you can chain on commands that you need, set up event handlers and append it to the DOM. For example

然后您可以链接您需要的命令,设置事件处理程序并将其附加到 DOM。例如

$('<div id="myid">Div Content</div>')
    .bind('click', function(e) { /* event handler here */ })
    .appendTo('#myOtherDiv');

回答by Igor Maculewicz

So far best solution that I've made:

到目前为止,我提出的最佳解决方案:

function convertHtmlToJQueryObject(html){
    var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
    return $(htmlDOMObject.documentElement);
}