This time I will bring you a detailed explanation of the common addition, deletion, modification and query operations of JS DOM elements. What are theprecautionsfor the common addition, deletion, modification and query operations of JS DOM elements. The following is a practical case, let's take a look.
DOM concept
DOM (Document Object Model): Document Object Model.
You can view it through the Elements tab of the developer tool
You can also observe that the entire document has a series of nodes through the Sources tab of the developer tool
The entire document is composed of A tree composed of a series of node objects.
Node (Node) includes element node (1), attribute node (2), text node (3) (1..2..3..represents the node type)_
var th1= document.getElementById("th1"); alert(th1.nodeType); alert(th1.nodeName); alert(th1.nodeValue);
th1 represents an element node (nodeType=1), nodeName is the label name (th), and nodeValue=null of the element node.
var attr1=th1.getAttributeNode("name"); alert(attr1.nodeType); alert(attr1.nodeName); alert(attr1.nodeValue);
The getAttributeNode method is to get the attribute node of the element. At this time, the output node type is the attribute node (2), the node name is the attribute name (name), and the node value is the attribute value (sex)
var txtl = th1.firstChild; alert(txtl.nodeType); alert(txtl.nodeName); alert(txtl.nodeValue)
txt1 is a text node (3), the node name is fixed to #text, and the node value is the text content.
Get the element
(1)getElementByid
Get the element based on the id attribute of the element. What you get is a element.
Get elements based on the tag name, and the result is a collection of elements.
(3)getElementsByClassName
Get elements based on the class attribute, and the result is a collection of elements.
(4)getElementsByName
Get elements based on the name attribute, and the result is a collection of elements.
Summary:Obtaining elements can be obtained based on the tag name, or based on the id, name, and class attributes. The result obtained based on the id attribute is an element, while the other results are a collection.
The document object supports the above four types, while the element object only supportsgetElementsByTagName
andgetElementsByClassName
.
Modify elements
(1) Modify content
function fun(){ //获取到指定元素 var p1 = document.getElementById("p1"); p1.innerText = "我被单击了!"; }
The content text of the label can be read or set through the .innerText property
function fun(){ //获取到指定元素 var p1 = document.getElementById("p1"); p1.innerHTML = "我被单击了!
换行了"; }
You can also get or set the content text through innerHTML attributes
The difference between the two: innerHTML will parse the text according to HTML rules, while innerText will just treat it as ordinary text content.
(1) Modify style
A. xxx. style.Attribute name="value"
B. xxx. classname="..." (equivalent to modifying the attributes of class)