jQuery Learning-DOM (1): jQuery creates elements and adds attributes

Link to the original text of this article: https://blog.csdn.net/xzk9381/article/details/112601903

Use jQuery to create elements and add attributes, you can directly use $('element') to add:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="jquery-1.12.4.js"></script>
	<script type="text/javascript">
		$('document').ready(function (){
     
     
			console.log($('<div></div>'))
		})
	</script>
</head>
<body>
</body>
</html>

This will generate a div tag. If you want to add text to this div tag, you can add it directly:

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

Next is to add attributes to the element:

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

If you want to create a multi-level label, you can also add string content directly in it:

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

It should be noted that the elements created above are stored in memory and have not been added to the page. You can use console.log to print the detailed information of the label.

Link to the original text of this article: https://blog.csdn.net/xzk9381/article/details/112601903

Guess you like

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