How can I convert a DOM element to a jQuery element?
Asked Answered
H

3

321

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

$("#id") 

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

Huebner answered 9/3, 2009 at 11:56 Comment(1)
This quesion should be awarded as the best question in stackoverflowDelia
C
518
var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element
Canner answered 9/3, 2009 at 11:58 Comment(6)
This works because jquery will take not only a string selector, but an existing jquery object, or any valid dom object as an argument to the main $() query function.Rottenstone
What about the reverse? You have a jquery element and want to convert it to a dom element?Longrange
The reverse can be done by: johnjianfang.blogspot.com/2009/04/…Longrange
Hey @Canner will this work if elm contains a collection of DOM nodes?Scratches
I'm getting this error... gist.github.com/CrazyPython/365615598342b220dc5735235682f0e3Standice
@Scratches yesBedchamber
R
17

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

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

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

$("<div>")

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

$('<div id="myid">Div Content</div>')
    .bind('click', function(e) { /* event handler here */ })
    .appendTo('#myOtherDiv');
Richelieu answered 9/3, 2009 at 12:11 Comment(1)
actually i am getting the element from somewhere where i cant change the codeHuebner
F
3

So far best solution that I've made:

function convertHtmlToJQueryObject(html){
    var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
    return $(htmlDOMObject.documentElement);
}
Fullmer answered 30/8, 2019 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.