Jquery gets that outerHtml contains the code for the current node itself

  • 2020-03-30 04:12:44
  • OfStack

In the development process, jquery.html () is to get the HTML code under the current node, not the code of the current node itself, and then we sometimes really need to look through the jQuery API documentation and there is no way to get it.

If you see someone passing through parent().html(), if the current element is okay without a sibling, then it won't work. Later, the experiment found that there is a solution of jQuery, and it is very simple, as follows:

JQuery. Prop (" outerHTML ");


<div class="test"><p>hello , how are you? </p></div>
<script>
$(".test").prop("outerHTML");
</script>

The output result is: < Div class = "test" > < P> Hello, how are you? < / p> < / div>

Because the native JS DOM has a built-in property, outerHTML (see case sensitive), which is used to get the HTML code of the current node (including the current node). Therefore, prop() can be obtained with jQuery, but attr() method cannot be obtained after experiment. If you don't believe me, you can also try it.

Of course, some people use jQuery's clone() function with append() to create a node with only one child and then get the HTML for the node. This is also possible, but the code is tedious.


Related articles: