jQuery Learning-DOM (3): jQuery inserts elements outside the DOM

Original link of this article: https://blog.csdn.net/xzk9381/article/details/112906894

1. Insert an element after the set of matched elements

Use the after() method to insert elements after the set of matched elements:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="jquery-1.12.4.js"></script>
	<script type="text/javascript">
		$('document').ready(function (){
     
     
			$('.div1').after($('<div class="mydiv" id="div2">测试</div>'))
         // $('.div1').after('<div class="mydiv" id="div2">测试</div>') 也可以直接写成这种形式
		})
	</script>
</head>
<body>
	<div class="div1">div测试</div>
	<div class="div1">div测试</div>
</body>
</html>

Using $('content').insertAfter('DOM') can also achieve this function, but the location of the content and the target are different:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="jquery-1.12.4.js"></script>
	<script type="text/javascript">
		$('document').ready(function (){
     
     
			$('<div class="mydiv" id="div2">测试</div>').insertAfter('.div1')
		})
	</script>
</head>
<body>
	<div class="div1">div测试</div>
	<div class="div1">div测试</div>
</body>
</html>

2. Insert an element before the set of matched elements

Use the before() method to insert elements before the set of matched elements:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="jquery-1.12.4.js"></script>
	<script type="text/javascript">
		$('document').ready(function (){
     
     
			$('.div1').before($('<div class="mydiv" id="div2">测试</div>'))
         // $('.div1').before('<div class="mydiv" id="div2">测试</div>') 也可以直接写成这种形式
		})
	</script>
</head>
<body>
	<div class="div1">div测试</div>
	<div class="div1">div测试</div>
</body>
</html>

This function can also be achieved by using $('content').insertBefore('DOM'), but the position of the content and the target are different:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="jquery-1.12.4.js"></script>
	<script type="text/javascript">
		$('document').ready(function (){
     
     
			$('<div class="mydiv" id="div2">测试</div>').insertBefore('.div1');
		})
	</script>
</head>
<body>
	<div class="div1">div测试</div>
	<div class="div1">div测试</div>
</body>
</html>

Original link of this article: https://blog.csdn.net/xzk9381/article/details/112906894

Guess you like

Origin blog.csdn.net/xzk9381/article/details/112906894