Home >Web Front-end >JS Tutorial >JQuery's method of replacing DOM nodes_jquery

JQuery's method of replacing DOM nodes_jquery

WBOY
WBOYOriginal
2016-05-16 15:55:531147browse

The example in this article describes how to replace DOM nodes with JQuery. Share it with everyone for your reference. The specific analysis is as follows:

If you want to replace a node, jQuery provides the corresponding methods, namely replaceWith() and replaceAll().

The function of the

replaceWith() method is to replace all matching elements with specified HTML or DOM elements.

JQuery code for this example:

<script type="text/javascript">
//<![CDATA[
$(function(){
 $("#btn_1").click(function(){
  $(".nm_p").replaceWith('<p class="nm_p">欢迎访问www.jb51.net</p>'); 
 })
 $("#btn_2").click(function(){
  $(".nm_p").replaceWith('<p class="nm_p" title="欢迎访问脚本之家" >欢迎访问脚本之家</p>'); 
  // 同样的实现: $('<p class="nm_p">欢迎访问www.jb51.net</p>').replaceAll(".nm_p"); 
 })
});
//]]>
</script>

You can also use another method in JQuery, replaceAll(), which has the same effect as the replaceWith() method, except that the replaceWith() operation is reversed. You can use the following jQuery code to achieve the same function:

Copy code The code is as follows:
$('cddd540254aab270c03b55130e145da7Welcome to www.jb51 .net94b3e26ee717c64999d7867364b1b4a3').replaceAll(".nm_p");

These two sentences of JQuery code will achieve the node replacement effect.

PS: If an event has been bound to an element before replacement, the originally bound event will disappear together with the replaced element after replacement, and the event needs to be re-binded on the new element.

I hope this article will be helpful to everyone’s jQuery programming.

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