JavaScript HTML DOM elements (nodes)

Create HTML elements

var newEle =document.createElement(p);

The created element is appended to other elements:

A. appendChild(B): If B is a newly created element, add element B to the end of all child elements of the A element.

If the element already exists in page B, the effect of this statement is to move the element B to the child element of A.

appendChild() This function has similar effects to the innerHTML attribute. The difference is:

1 innerHTML will run slower than appendChild (maybe because it needs to be parsed)

2 innerHTML is more convenient than appendChild, just like writing a string

    php中文网(php.cn) 

这是一个段落。

这是另一个段落。

Example analysis:

This code creates a new

element:

var para=document.createElement("p");

To add text to a

element, you must first create a text node. This code creates a text node:

var node=document.createTextNode("This is a new paragraph.");

Then you have to

Element appends this text node:

para.appendChild(node);

Finally you must append this new element to an existing element.

This code finds an existing element:

var element=document.getElementById("div1");

The following code is already Add new elements after existing elements:

element.appendChild(para);


Delete HTML elements

The removechild function can delete the specified child elements of the parent element.

If this function successfully deletes the child node, it returns the deleted node, otherwise it returns null.

Syntax structure:

fatherObj.removeChild(childrenObj)

Parameter explanation:

1.fatherObj: The element object of the child element to be deleted.
2.childrenObj: The child element object to be deleted.

    php中文网(php.cn) 

这是一个段落。

这是另一个段落。

Example analysis

This HTML document contains a

element with two child nodes (two

elements):

这是一个段落。

这是另一个段落。

Find the element with id="div1":

var parent=document.getElementById("div1");

Find the element with id="p1"

Element:

var child=document.getElementById("p1");

Remove child element from parent element:

parent.removeChild(child);
Continuing Learning
||
php中文网(php.cn)
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!