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
$('<p><a>jQuery</a></p>').find('a').attr('href', '') 

Finally, the newly added p element is added to the body
$('<p><a>jQuery</a></p>').find('a').attr('href', '').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> 
<meta charset="UTF-8"> 
<script type="text/javascript" src="jquery-1.11.1.js"></script> 
<script type="text/javascript"> 
$('<p><a>jQuery</a></p>').find('a').attr('href', '').appendTo('body'); 

Page code
< img SRC = "border = 0 / / 20144209442 ">

Related articles: