This time I will bring youJavaScriptA detailed explanation of the steps for adding, deleting, and modifying DOM elements. What are theprecautions for adding, deleting, and modifying JavaScript 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);
var attr1=th1.getAttributeNode("name"); alert(attr1.nodeType); alert(attr1.nodeName); alert(attr1.nodeValue);
var txtl = th1.firstChild; alert(txtl.nodeType); alert(txtl.nodeName); alert(txtl.nodeValue)
Get the element
(1)getElementByid
Get the element based on the id attribute of the element. What you get is a element. (2) 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 supportsgetElementsByTagNameand
getElementsByClassName.
Modify elements
(1) Modify contentfunction fun(){ //获取到指定元素 var p1 = document.getElementById("p1"); p1.innerText = "我被单击了!"; }
function fun(){ //获取到指定元素 var p1 = document.getElementById("p1"); p1.innerHTML = "我被单击了!
换行了"; }