Keywords for dynamically creating elements in JavaScript and jQuery ~, Javascriptjquery
JavaScript dynamic element creation:
1. Create elements such as a tag
Var alink = document. createElement ("");
2. Add element attributes to j.
Alink. href = "http://www.abc.com ";
Alink.tar get = "_ blank ";
OrAlink. setAttribute ("href", "http://www.abc.com"); // set the property href value to http://www.abc.com
3. Add the created element to the element with id
GetElementById ("# id"). appendChild (alink );
Supplement: Create a table
Var table = document. createElement ("table ");
Var row = table. isertRow (-1); // (-1) indicates adding row (tr) to table
Var td1 = row. insertCell (-1) (-1) indicates adding a cell (td) to tr
Ducument. body. addendChild (table); add table to body
JQuery dynamic creation element:
1. Create elements and add attributes, such as tag.
Var alink = $ ("<a href =" http://www.abc.com "target =" _ blank "title =" this is a link "> ");
2. Add the created element to the element with id
$ ("# Id"). append (alink); // Add passively
The above two steps are equivalent:
$ ("<A href =" http://www.abc.com "target =" _ blank "title =" this is a link ">"). appendTo ("# id"); // actively add
Note: keywords
1,Propend/propendToAdd the created element to the front of the element (that is, as a lower-level element)
2. Add the created element to the end of the element (that is, as a lower-level element)
3,Before/insertBeforeAppend the created element to the front of the element (that is, as a sibling element)
4,After/insertAfterAppend the created element to the end of the element (that is, as a sibling element)