How do you convert a jQuery object into a string?

前端 未结 12 1836
臣服心动
臣服心动 2020-11-22 15:07

How do you convert a jQuery object into a string?

相关标签:
12条回答
  • 2020-11-22 15:19

    No need to clone and add to the DOM to use .html(), you can do:

    $('#item-of-interest').wrap('<div></div>').html()
    
    0 讨论(0)
  • 2020-11-22 15:20

    I assume you're asking for the full HTML string. If that's the case, something like this will do the trick:

    $('<div>').append($('#item-of-interest').clone()).html(); 
    

    This is explained in more depth here, but essentially you make a new node to wrap the item of interest, do the manipulations, remove it, and grab the HTML.

    If you're just after a string representation, then go with new String(obj).

    Update

    I wrote the original answer in 2009. As of 2014, most major browsers now support outerHTML as a native property (see, for example, Firefox and Internet Explorer), so you can do:

    $('#item-of-interest').prop('outerHTML');
    
    0 讨论(0)
  • 2020-11-22 15:20

    The best way to find out what properties and methods are available to an HTML node (object) is to do something like:

    console.log($("#my-node"));
    

    From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output:

    var node = $("#my-node").outerHTML;
    
    0 讨论(0)
  • 2020-11-22 15:21

    It may be possible to use the jQuery.makeArray(obj) utility function:

    var obj = $('<p />',{'class':'className'}).html('peekaboo');
    var objArr = $.makeArray(obj);
    var plainText = objArr[0];
    
    0 讨论(0)
  • 2020-11-22 15:21
    new String(myobj)
    

    If you want to serialize the whole object to string, use JSON.

    0 讨论(0)
  • 2020-11-22 15:24

    This seems to work fine for me:

    $("#id")[0].outerHTML
    
    0 讨论(0)
提交回复
热议问题