Home  >  Article  >  Web Front-end  >  jquery gets outerHtml containing the code of the current node itself_jquery

jquery gets outerHtml containing the code of the current node itself_jquery

WBOY
WBOYOriginal
2016-05-16 16:32:371027browse

During the development process, jQuery.html() obtains the html code under the current node, and does not include the code of the current node itself. Sometimes we really need it, but there is no way to get it even after searching through the jQuery api documentation. .

I saw that some people use parent().html(). If the current element does not have sibling elements, it will work, but if it does, it will not work. Later, the experiment found that there is a jQuery method that can solve the problem, and it is very simple, as follows:

jQuery.prop("outerHTML");

Copy code The code is as follows:

hello!


<script><br> $(".test").prop("outerHTML");<br> </script>

The output result is:

hello, hello!

Because there is a built-in attribute outerHTML in the native JS DOM (look at the case, JS is case-sensitive) to get the html code of the current node (including the current node), so you can use jQuery's prop() to get it Yes, after experiments, the attr() method cannot be obtained. If you don’t believe it, you can try it. Thank you.

Of course, some people use jQuery's clone() function together with append() to create a node with only one child element, and then get the node's html. This is also feasible, but the code is cumbersome.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn