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

Jquery

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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');

Solution 3 - Jquery

So far best solution that I've made:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTanmoyView Question on Stackoverflow
Solution 1 - JqueryMariusView Answer on Stackoverflow
Solution 2 - JqueryRuss CamView Answer on Stackoverflow
Solution 3 - JqueryIgor MaculewiczView Answer on Stackoverflow