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

ID : 10185

viewed : 24

Tags : jqueryjquery

Top 5 Answer for How can I convert a DOM element to a jQuery element?

vote vote

90

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

88

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

74

So far best solution that I've made:

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

66

vote vote

51

To get an attribute to show a specific value based on a boolean check, or be omitted entirely if the boolean check failed, I used the following:

ng-attr-example="{{params.type == 'test' ? 'itWasTest' : undefined }}"

Example usage:

<div ng-attr-class="{{params.type == 'test' ? 'itWasTest' : undefined }}">

Would output <div class="itWasTest"> or <div> based on the value of params.type

Top 3 video Explaining How can I convert a DOM element to a jQuery element?

Related QUESTION?