Home  >  Article  >  Web Front-end  >  How to replace dom elements with jquery

How to replace dom elements with jquery

WBOY
WBOYOriginal
2022-06-13 17:35:022032browse

Method: 1. Use the replaceWith() method, which is used for all matching elements in the collection. The syntax is "element object.replaceWith(content, function(index))"; 2. Use replaceAll() Method, which is used to replace selected elements with new HTML elements. The syntax is "element object.replaceAll(selector)".

How to replace dom elements with jquery

The operating environment of this tutorial: windows10 system, jquery3.6.0 version, Dell G3 computer.

How to replace dom elements with jquery

1. replaceWith() method

$(selector).replaceWith(content,function(index))

content is required. Specifies the content to be inserted (can include HTML tags).

Possible values:

  • HTML element

  • jQuery object

  • DOM element

#function(index) Optional. Specifies a function that returns replacement content.

index - Returns the index position of the element in the collection.

$(DOM).replaceWith(newContent) is used to replace all matching elements in the collection and return the deleted element collection:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(&#39;document&#39;).ready(function (){
$(&#39;body>input&#39;).click(function (){
$(&#39;body>ul>li:gt(1)&#39;).replaceWith(&#39;<li>替换后的元素</li>&#39;)
})
})
</script>
</head>
<body>
<input type="button" value="替换">
<ul>
<li>第一个</li>
<li>第二个</li>
<li>第三个</li>
<li>第四个</li>
</ul>
</body>
</html>

Output result:

How to replace dom elements with jquery

2. replaceAll() method

$(newContent).replaceAll(DOM) has the same function as $(DOM).replaceWith(newContent), only But the parameter position is changed (you can directly assign the style later):

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(&#39;document&#39;).ready(function (){
$(&#39;body>input&#39;).click(function (){
$(&#39;<li>替换后的元素</li>&#39;).replaceAll(&#39;body>ul>li:gt(1)&#39;).css(&#39;color&#39;,&#39;orange&#39;);
})
})
</script>
</head>
<body>
<input type="button" value="替换">
<ul>
<li>第一个</li>
<li>第二个</li>
<li>第三个</li>
<li>第四个</li>
</ul>
</body>
</html>

Output result:

How to replace dom elements with jquery

Video tutorial recommendation: jQuery video Tutorial

The above is the detailed content of How to replace dom elements with jquery. For more information, please follow other related articles on the PHP Chinese website!

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