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

前端 未结 3 571
忘了有多久
忘了有多久 2020-11-28 17:44

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

相关标签:
3条回答
  • 2020-11-28 17:57
    var elm = document.createElement("div");
    var jelm = $(elm);//convert to jQuery Element
    var htmlElm = jelm[0];//convert to HTML Element
    
    0 讨论(0)
  • 2020-11-28 18:10

    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');
    
    0 讨论(0)
  • 2020-11-28 18:18

    So far best solution that I've made:

    function convertHtmlToJQueryObject(html){
        var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
        return $(htmlDOMObject.documentElement);
    }
    
    0 讨论(0)
提交回复
热议问题