Home > Web Front-end > JS Tutorial > body text

JavaScript complete summary of DOM Elements

jacklove
Release: 2018-05-21 14:00:31
Original
1859 people have browsed it

We often encounter some problems with javascript dom in our studies, so this article will explain them.

In addition to the document object, the most commonly used element object in DOM is the Element object, which represents HTML elements.

Element objects can have child nodes of type element nodes, text nodes, and comment nodes. DOM provides a series of methods to add, delete, modify, and query elements

Element There are several important attributes

nodeName: element tag name, and a similar tagName
nodeType: element type
className: class name id: element idchildren: child element list (HTMLCollection)
childNodes: child element list (NodeList)
firstChild: the first child element
lastChild: the last child element
nextSibling: the next sibling element
previousSibling: the previous sibling element
parentNode , parentElement: parent element

Query element

getElementById
method returns the element node that matches the specified ID attribute. If no matching node is found, null is returned. This is also the fastest way to get an element.

var elem = document.getElementById("test");getElementsByClassName()
getElementsByClassName
Copy after login

The method returns an array-like object (HTMLCollection type object), including all elements whose class names meet the specified conditions (the search range includes itself), and changes in the elements. Reflected in the returned results in real time. This method can be called not only on the document object, but also on any element node.

var elements = document.getElementsByClassName(names);//getElementsByClassName方法的参数,可以是多个空格分隔的class名字,返回同时具有这些节点的元素。
Copy after login
document.getElementsByClassName('red test');```
* getElementsByTagName()
Copy after login

getElementsByTagName method returns all elements with the specified tag (the search scope includes itself). The return value is an HTMLCollection object, that is to say, the search results are a dynamic collection, and changes in any elements will be reflected in the returned collection in real time. This method can be called not only on the document object, but also on any element node.

var paras = document.getElementsByTagName("p");
//上面代码返回当前文档的所有p元素节点。注意,getElementsByTagName方法会将参数转为小写后,再进行搜索。```
Copy after login
getElementsByName()
getElementsByName方法用于选择拥有name属性的HTML元素,比如form、img、frame、embed和object,返回一个NodeList格式的对象,不会实时反映元素的变化。
Copy after login

// Assume there is a form

var forms = document.getElementsByName("x");
forms[0 ].tagName // "FORM" // Note that when using this method in IE browser, elements that do not have a name attribute but have an id attribute with the same name will also be returned, so it is best to set the name and id attributes to different values. ```* querySelector()
querySelector method returns element nodes that match the specified CSS selector. If multiple nodes meet the matching criteria, the first matching node is returned. If no matching node is found, null is returned.

var el1 = document.querySelector(".myclass");
var el2 = document.querySelector('#myParent > [ng-click]');
//querySelector方法无法选中CSS伪元素。```
Copy after login
querySelectorAll()
querySelectorAll方法返回匹配指定的CSS选择器的所有节点,返回的是NodeList类型的对象。NodeList对象不是动态集合,所以元素节点的变化无法实时反映在返回结果中。
Copy after login
elementList = document.querySelectorAll(selectors);//querySelectorAll方法的参数,可以是逗号分隔的多个CSS选择器,返回所有匹配其中一个选择器的元素。var matches = document.querySelectorAll("div.note, div.alert");//上面代码返回class属性是note或alert的div元素。
Copy after login
elementFromPoint()
elementFromPoint方法返回位于页面指定位置的元素。
Copy after login
var element = document.elementFromPoint(x, y);//上面代码中,elementFromPoint方法的参数x和y,分别是相对于当前窗口左上角的横坐标和纵坐标,单位是CSS像素。
Copy after login
elementFromPoint方法返回位于这个位置的DOM元素,如果该元素不可返回(比如文本框的滚动条),则返回它的父元素(比如文本框)。如果坐标值无意义(比如负值),则返回null。
Copy after login

Creating elements

createElement()
createElement方法用来生成HTML元素节点。
Copy after login
var newDiv = document.createElement("div");//createElement方法的参数为元素的标签名,即元素节点的tagName属性。//如果传入大写的标签名,会被转为小写。如果参数带有尖括号(即<和>)或者是null,会报错。
Copy after login
createTextNode()
createTextNode方法用来生成文本节点,参数为所要生成的文本节点的内容。
Copy after login
var newDiv = document.createElement("div");var newContent = document.createTextNode("Hello");//上面代码新建一个div节点和一个文本节点
createDocumentFragment()
Copy after login
//createDocumentFragment方法生成一个DocumentFragment对象。var docFragment = document.createDocumentFragment();```
Copy after login

The DocumentFragment object is a DOM fragment that exists in memory, but does not belong to the current document. It is often used to generate more complex DOM structures and then insert them into the current document. . The advantage of this is that because the DocumentFragment does not belong to the current document, any changes to it will not cause the web page to be re-rendered, which has better performance than directly modifying the DOM of the current document.

##Modify elements

* appendChild()
Add an element to the end of an element

var newDiv = document.createElement("div");var newContent = document.createTextNode("Hello");newDiv.appendChild(newContent);```
insertBefore()
Copy after login

Insert an element before an element

var newDiv = document.createElement("div");var newContent = document.createTextNode("Hello");newDiv.insertBefore(newContent, newDiv.firstChild);replaceChild()
replaceChild()
Copy after login

Accepts two parameters: the element to be inserted and the element to be replaced

newDiv.replaceChild(newElement, oldElement);```
* removeChild()
Copy after login

Delete element

parentNode.removeChild(childNode);```
cloneNode()
Copy after login

Clone element, the method has a boolean parameter , when true is passed in, it will be deeply copied, that is, the element and its sub-elements will be copied (IE will also copy its events), when false, only the element itself will be copied

node.cloneNode(true);```##属性操作* getAttribute()
//getAttribute()用于获取元素的attribute值node.getAttribute(&#39;id&#39;);```
createAttribute()
Copy after login
//createAttribute()方法生成一个新的属性对象节点,并返回它。attribute = document.createAttribute(name);
createAttribute方法的参数name,是属性的名称。
Copy after login

setAttribute()

//setAttribute()方法用于设置元素属性var node = document.getElementById("div1");
node.setAttribute("my_attrib", "newVal");//等同于var node = document.getElementById("div1");var a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);```
* romoveAttribute()
Copy after login
removeAttribute()用于删除元素属性
node.removeAttribute(&#39;id&#39;);
element.attributes
Copy after login

Of course, what the above method does can also be achieved by class operation array attribute element.attributes


#HTMLCollection and NodeList We know that the Element object represents an element, so a collection of multiple elements There are generally two data types. The NodeList object represents an ordered node list. HTMLCollection is an interface that represents a collection of HTML elements. It provides methods and attributes that can traverse the list.

The following method obtains the HTMLCollection object

document.images //所有img元素
document.links //所有带href属性的a元素和area元素
document.anchors //所有带name属性的a元素
document.forms //所有form元素
document.scripts //所有script元素
document.applets //所有applet元素
document.embeds //所有embed元素
document.plugins //document.与embeds相同
document.getElementById("table").children
document.getElementById("table").tBodies
document.getElementById("table").rows
document.getElementById("row").cells
document.getElementById("Map").areas
document.getElementById("f2").elements //HTMLFormControlsCollection extends HTMLCollection
document.getElementById("s").options //HTMLOptionsCollection extends HTMLCollection```
Copy after login

The following methods obtain NodeList objects

document.getElementsByName("name1")
document.getElementsByClassName("class1")
document.getElementsByTagName("a")
document.querySelectorAll("a")
document.getElementById("table").childNodes
document.styleSheets //StyleSheetList,与NodeList类似```#####HTMLCollection与NodeList有很大部分相似性* 都是类数组对象,都有length属性,可以通过for循环迭代
Copy after login

* are all read-only

* are real-time, that is, changes to the document will be immediately Reflected on the relevant objects (with one exception, the NodeList returned by document.querySelectorAll is not real-time)

* All have item() methods, and elements can be obtained through item(index) or item("id")
##The difference is that * HTMLCollection object has namedItem() method, you can pass id or name to obtain elements
* HTMLCollection's item() method and obtaining elements through attributes (document.forms.f1) can support id and name, while the NodeList object only supports id

###This article provides a relevant explanation of dom. For more related content, please pay attention to the php Chinese website. ###

The above is the detailed content of JavaScript complete summary of DOM Elements. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template