How to get html string of child tag and parent tag using jquery?

For example, if I have an HTML list ul, for example

<ul id="ulIdentificator"> 
    <li id="li0"></li>
    <li id="li1"></li>
    <li id="li2"><label id="label1"></label></li>   
</ul>

If I use jQuery as follows

var htmlStr = $("#li2").html();

The result will be only a string containing the tag tag. <LABEL id="label1"></LABEL></li>I need to get an HTML string containing this<LI id="li2"><LABEL id="label1"></LABEL></LI>

+3
source share
3 answers

Andres' second OuterHTML method mentions (from a web architects blog) works in all browsers, so this is probably the best choice. The basic idea is that you can get the external HTML element by making it another innerHTML element:

var outerHtml = $("<div/>").append($("#li2").clone()).html();

- , clone , DOM.

, , .

+6

jQuery Jeff Sternal:

// jQuery plugin 'htmlWithParent'

jQuery(function($) {

  $.fn.htmlWithParent = function() { return $j("<div/>").append($j(this).clone()).html(); };

});

cutom, :

var htmlCode = $("<p><span>Helo world!</span></p>");

// Return only child nodes: <span>Helo world!</span>
var output1 = $(htmlCode).html();

// Return whole HTML code (childs + parent): <p><span>Helo world!</span></p>
var output2 = $(htmlCode).htmlWithParent();

.;)

+1
0

Source: https://habr.com/ru/post/1725881/


All Articles