jQuery get DOM element as string

前端 未结 5 2077
走了就别回头了
走了就别回头了 2020-12-30 03:16

Say I have

$(\":input[type=text]:first\")

How do I get



        
相关标签:
5条回答
  • 2020-12-30 03:37

    Following on what @Blazemonger have answered, if you are going to send this html content to the server, it's worth to get rid of all unnecessary tags, white-spaces and line-breaks that don't add any value.

    var quote = $(".invoice") //get hidden print-version DOM element
        .clone()
        .wrap('<div/>')
        .parent()
        .html()
        .replace(/    /g, '') //get rid of indentation spaces
        .replace(/(\r\n|\n|\r)/gm, "") //get rid of line breaks
        .replace(/<!--[\s\S]*?-->/g, ""); //get rid of comment tags
    

    My html had 50kb, after getting rid of this stuff, it got reduced to 4kb!

    0 讨论(0)
  • 2020-12-30 03:49

    How about:

    var str = $(selector)[0]
    

    Maybe add a check that there is one element returned.

    0 讨论(0)
  • 2020-12-30 03:52

    Use jQuery.html() by appending to a created element.

    $('<div/>').append($(":input[type=text]:first").clone()).html()
    

    Here is a fiddle providing an example: http://jsfiddle.net/Zwbmx/1/

    0 讨论(0)
  • 2020-12-30 03:57

    An old trick:

    var selector = ":input[type=text]:first";
    
    var str = $(selector).clone().wrap('<div/>').parent().html();
    

    Update You don't need to worry about calling .parent() since you're working with an orphaned clone of the original selector.

    0 讨论(0)
  • 2020-12-30 03:58

    How about

    $(selector).prop("outerHTML");
    
    0 讨论(0)
提交回复
热议问题