How do you create modify and then add DOM elements to jQuery
- 2020-03-30 03:02:11
- OfStack
How do you manipulate DOM elements on the fly?
For example, sequential execution [create] -> [modification] -> [add] three actions.
Since jQuery supports chained operations, which is essentially the builder mode of design mode, we can string all three operations together.
You first create a p element, and the content contains an a element.
Then add an href attribute to the a element
Finally, the newly added p element is added to the body
Notice that this is where the end() operation needs to be done, otherwise the element added to the body is not a p element but an a element in a p element.
In fact, the end() operation is not equivalent to undo, it returns a previous selection, but this selection has been modified by the operation before end.
Page code
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/201405200943482.gif? 20144209442 ">
For example, sequential execution [create] -> [modification] -> [add] three actions.
Since jQuery supports chained operations, which is essentially the builder mode of design mode, we can string all three operations together.
You first create a p element, and the content contains an a element.
$('<p><a>jQuery</a></p>')
Then add an href attribute to the a element
$('<p><a>jQuery</a></p>').find('a').attr('href', 'http://www.jquery.com')
Finally, the newly added p element is added to the body
$('<p><a>jQuery</a></p>').find('a').attr('href', 'http://www.jquery.com').end().appendTo('body')
Notice that this is where the end() operation needs to be done, otherwise the element added to the body is not a p element but an a element in a p element.
In fact, the end() operation is not equivalent to undo, it returns a previous selection, but this selection has been modified by the operation before end.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script type="text/javascript">
$('<p><a>jQuery</a></p>').find('a').attr('href', 'http://www.jqeury.com').appendTo('body');
</script>
</body>
</html>
Page code
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201405/201405200943482.gif? 20144209442 ">