Home > Web Front-end > JS Tutorial > Detailed explanation of DOM attribute methods and compatibility issues

Detailed explanation of DOM attribute methods and compatibility issues

巴扎黑
Release: 2017-08-09 14:05:41
Original
1315 people have browsed it

Element type in DOM: (All the following attributes are only read-only attributes)

1. node.nodeType Returns the node of the specified node as a numeric value type.

There are 12 different node types, among which there may be child nodes of different node types (the first three are important):
Detailed explanation of DOM attribute methods and compatibility issues

if(ul .nodeType == Node.ELEMENT_NODE){
alert(‘Node is an element’);
}
The above code can run normally under standard browsers, but cannot run normally under non-standard browsers (under ie8).
Solution:
if(ul.nodeType ==1){ alert(‘Node is an element’); } Use the nodeType attribute to compare with numbers.

2. The nodeName value is the tag name of the element type, such as ul, p, etc.
nodeValue value is null.
ParentNode may be document or Element, and child nodes may be. Element,Text,Comment,ProcessingInstruction,CDATASection,EntityReference.

Operation characteristics

1. How to obtain attributes of HTML elements

All HTML elements pass the HTMLElement type or its subtypes (HTMLDivElement, HTMLImageElement ) indicates that the HTMLElement type inherits from the Element type, but adds some unique attributes. The subtype also has its own unique attributes and methods. For example, img has unique attributes such as src and title. Special note is that since class is a keyword in js, className must be used to obtain the value of class.

The acquisition and setting methods and the places to pay attention to are described by comparison in 23.

2. element.getAttribute(attributename) returns the attribute value of the specified attribute name.

This method passes in a string of attribute names, which is not case-sensitive.
For example, ul.getAttribute(‘class’); Since the parameter is a string, you can use class without using className. Custom attributes can be obtained through this method. In some attribute names that contain characters used in non-keywords, it is particularly convenient to use this method to obtain the value of the attribute. For example, in the HTML5 specification, custom attributes should be preceded by the data- prefix. To facilitate verification, if it contains the illegal character '-', you can use ul.getAttribute('data-index'); to obtain it.

Specially, when attributename is style, this method returns an object in versions before IE7, and other versions of browsers return CSS text. When attributename is an event handler such as onclick, this method returns a method or null in versions before IE7, and other versions of browsers return a function code string.

Obtaining attributes through HTML element attributes is quite different from getAttribute().
1. Differences in custom attribute access:
When parsing html code, standard browsers will not add the custom attributes of elements to the DOM object. Custom attributes are accessed in js through attributes. If the attribute does not exist, the result is undefined. Non-standard browsers will add this custom attribute to the DOM object, and the result will be accessed in js.

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <ul id="ul1"  index="hehe">            <li>11111111</li>            <li>22222222</li>            <li>33333333</li>            <li>44444444</li>        </ul>        <script type="text/javascript">            var ul = document.getElementById(&#39;ul1&#39;);
            alert(ul.id);     /*标准与非标准都是div1*/
            alert(ul.index);/*标准为undefined 非标准为hehe*/        </script>    </body></html>123456789101112131415161718192021
Copy after login

2. When the attribute is style, an object is returned. When the attribute is event handling, the copied function is returned.

To sum up, when manipulating DOM object attributes, HTML element attributes are generally used to obtain attributes. Only when obtaining the value of custom attributes and some attribute names containing illegal characters When using the getAttribute method.

.

3. element.setAttribute(attributename, attributevalue) adds the specified attribute and assigns it the specified value.

Compared with the way of setting attributes through HTML element attributes, this method can add some custom attributes that are not available and assign values, but the attributes set through HTML element attributes will not be set. At the same time, this method also has exceptions in versions before IE7, so in addition to setting custom attributes, there are other ways to set properties through HTML element attributes.

4. RemoveAttribute() removes attributes, but is not used frequently. Versions before IE6 do not support this method.

Operation content

1. childNodes: represents a collection of child nodes of an element and returns a NodeList object.

Under standard browsers: the returned child nodes include text type, element type, comment type, etc., especially empty text in the text type, which is the so-called line break.
In non-standard browsers: the returned child nodes do not contain text type hollow text, and are also related to the node position, parsing method, etc.

<ul id="ul1">            <li>22222</li>
            111111            <!--33333--></ul><script type="text/javascript">    var oul = document.getElementById(&#39;ul1&#39;);
    alert(oul.childNodes.length);</script>在标准浏览器下:得到的结果为5(li元素前的换行空文本,li元素,注释到</li>之间这一段文本,注释,注释到</ul>的空白) 在非标准的浏览器下得到的结果为1 但是将<li>22222</li>  111111互换位置之后得到的结果为2.1234567891011
Copy after login
所以当运行下面代码的时候为出问题:<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">    </head>    <body>        <ul id="ul1">            <li>11111111</li>            <li>22222222</li>            <li>33333333</li>            <li>44444444</li>        </ul>        <script type="text/javascript">            var oul = document.getElementById(&#39;ul1&#39;);            for(var i = 0; i<oul.childNodes.length; i++){
                oul.childNodes[i].style.backgroundColor = &#39;red&#39;;
            }        /*标准: Cannot set property &#39;backgroundColor&#39; of undefined*/        /*非标准:(ie8之前)正常*/   
        </script>    </body></html>原因很简单,就是因为在标准浏览器下childNodes返回的子节点中包含非元素类型的节点。12345678910111213141516171819202122232425
Copy after login

Ways to solve the above problem:
Determine whether the child node is an element type through the nodeType attribute:

for(var i = 0; i<oul.childNodes.length; i++){
    if(oul.childNodes[i].nodeType === 1)
oul.childNodes[i].style.backgroundColor = &#39;red&#39;;
}1234
Copy after login

In illegally nested html documents, due to different parsing methods, in standard and The results presented in non-standard browsers are different, which is entirely related to the parsing method of the browser kernel. for example:

<!doctype html>    <html lang="en">    <head>        <meta charset="UTF-8" />    </head>    <body>        <ul id="ul1">            <li>11111111</li>            <li>22222222</li>            <li>33333333</li>            <li>44444444</li>            <p>5555555</p>        </ul>        <script type="text/javascript">            var oul = document.getElementById(&#39;ul1&#39;);            for(var i = 0; i<oul.childNodes.length; i++){                if(oul.childNodes[i].nodeType === 1)
                oul.childNodes[i].style.backgroundColor = &#39;red&#39;;
            }        </script>    </body>    </html>1234567891011121314151617181920212223
Copy after login

对于一些分标准的浏览器比如ie7 解析的时候他会把这种那个不符合语义的p元素放到最后一个li中,但对于其他的浏览器并不会这样。换句话说,在标准浏览器下p是ul的子节点,但是在非标准的浏览器下p是最后一个li的子节点,这完全和浏览器内核的系欸小方式有关。

由此可以看出,对于在书写html文档的时候,结构化语义是多么的重要,至少能为添加js方便不少。

二、element.childern仅仅返回元素类型的子节点集合,返回NodeList 对象。

Children比childNodes要好得多,因为他仅仅获取那些为元素类型的子节点。但是还是不能免于非法嵌套带来的问题,这本身至于浏览器的近稀饭时有关,与用那种属性没有关系。

三、element.firstChild(firstElementChild):获取第一个子点
element.lastChild(lastElementChild):获取最后一个子节点
element.nextSibling(nextElementSibling):获取相邻的下一个兄弟子节点
element.previousSibling(previousElementSibling):获取相邻的上一个兄弟节点

以firstChild为例说明一下性质,其他的大同小异。
在标准情况下:返回的结果可能是文本类型(空文本)。
在非标准的情况下:如果有元素子节点,那么一定返回第一个元素类型的子节点。

<!doctype html><html lang="en"><head>    <meta charset="UTF-8" /></head><body>    <ul id="ul1">            <li>11111111</li>            <li>22222222</li>            <li>33333333</li>            <li>44444444</li>    </ul>    <script type="text/javascript">        var oul = document.getElementById(&#39;ul1&#39;);
            alert(oul.firstChild.nodeName);            /*标准下text非标准为li*/    </script></body></html>123456789101112131415161718192021
Copy after login

解决这种情况
1是firstElementChild。
firstElementChild仅仅是在标准浏览器下有效,在非标准的浏览器下是没有定义的。在标准浏览器下仅仅返回第一个元素类型的子节点,如果没有返回null。
再js中加入:

function firstChild(obj){                if(obj.firstElementChild === undefined){//检测是否为标准浏览器                    return obj.firstChild;//不是标准浏览器,用firstChild返回第一个元素子节点,可能为null
                }else{                    return obj.firstElementChild;//是标准浏览器,用firstElementChild返回第一个元素子节点,可能为null
                }
            }            var oFirst = firstChild(oul);            if(oFirst){//判断有没有第一个元素子节点排除空节点的情况
                oFirst.style.backgroundColor = &#39;orange&#39;;
            }else{
                alert(&#39;没有第一个元素&#39;);
            }123456789101112131415
Copy after login

2直接用children:推荐

if(oul.children[0]){
                oul.children[0].style.backgroundColor = &#39;orange&#39;;
            }else{
                alert(&#39;没有第一个元素&#39;);
            }123456
Copy after login

四、element.parentNode: 当前节点的父级节点,无兼容性问题。

Eg:点击隐藏将这个列表隐藏<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>无标题文档</title><script>window.onload = function() {    var aA = document.getElementsByTagName(&#39;a&#39;);    for (var i=0; i<aA.length; i++) {   
        aA[i].onclick = function() {            this.parentNode.style.display = &#39;none&#39;;     
        }   
    }
}</script></head><body>    <ul id="ul1">        <li>11111 <a href="javascript:;">隐藏</a></li>        <li>22222 <a href="javascript:;">隐藏</a></li>        <li>33333 <a href="javascript:;">隐藏</a></li>        <li>44444 <a href="javascript:;">隐藏</a></li>    </ul></body></html>123456789101112131415161718192021222324252627
Copy after login

五、element.offsetParent : 只读 属性 离当前元素最近的一个有定位属性的父节点

非ie7以下的浏览器:
如果没有定位父级 offsetParent 为body
如果有定位父级 offsetParent 为定位父级
Ie7以下的浏览器:
如果没有定位父级 自身没有定位 offsetParent 为body,自身有定位的话 为html
如果当前元素的某个父级触发了layout,那么offsetParent就会被指向到这个触发了layout特性的父节点上。

如果有定位父级 offsetParent 为定位父级

<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>无标题文档</title><style>div {padding: 40px 50px;}#div1 {background: red;}#div2 {background: green; zoom: 1;position: relative;}#div3 {background: orange;}</style><script>window.onload = function() {    var oDiv3 = document.getElementById(&#39;div3&#39;);
    alert( oDiv3.offsetParent.id ); 
}</script></head><body id="body1">    <div id="div1">        <div id="div2">            <div id="div3"></div>        </div>    </div></body></html>1234567891011121314151617181920212223242526272829
Copy after login

Div2 zoom:1;属性触发layout,并且div3没有定位,所以在ie7一下的版本父元素div2,同时,div2相对定位,在其他浏览器中父元素为div2。解决了兼容性问题。

六、element.offsetLeft[Top] : 只读 属性
当前元素到定位父级的距离(偏移值)(或者说,到当前元素的offsetParent的距离)

非ie7以下的浏览器:
如果没有定位父级 offsetLeft [top]是到html的距离。
如果有定位父级 是到定位父级的距离。
ie7以下:
如果自己没有定位,无论是否有没有父级定位offsetLeft[Top]是到body的距离
如果自己有定位,那么就是到定位父级的距离(没有父级定位情况下是到html的距离)。

<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>无标题文档</title><style>div {padding: 40px 50px;}#div1 {background: red;}#div2 {background: green; position: relative;}#div3 {background: orange; position: relative;}</style><script>window.onload = function() {    var oDiv3 = document.getElementById(&#39;div3&#39;);
    alert( oDiv3.offsetTop );
}</script></head><body id="body1">    <div id="div1">        <div id="div2">            <div id="div3"></div>        </div>    </div></body></html>123456789101112131415161718192021222324252627
Copy after login
例子:获得任意一个元素的相对
于页面的位置<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <style type="text/css">            body{padding:0; margin:0;}            /*由于offsetLeft和offsetParsent在没有定位父级的时候父级不同*/            div{padding: 40px 50px;}            #div1{background-color: #008000;}            #div2{background-color: #FF0000;position: relative;}            #div3{background-color: #FFA500;position:relative;}            /*设置position offsetLeft在字节没有定位的时候是相对body的*/        </style>    </head>    <body>        <div id="div1">            <div id="div2">                <div id="div3"> 
                </div>            </div>        </div>        <script type="text/javascript">            var oDiv = document.getElementById(&#39;div3&#39;);            function getPosition(obj){                var pos = {left:0, top:0};                while(obj){
                    pos.left += obj.offsetLeft;
                    pos.top +=obj.offsetTop;
                    obj = obj.offsetParent; 
                }                return pos;
            }
            alert(getPosition(oDiv).left);        </script>    </body></html>12345678910111213141516171819202122232425262728293031323334353637383940414243444546
Copy after login

七、长高:
element.style.width : 样式宽 = width
element.clientWidth : 可视区宽 = width + padding
element.offsetWidth: 占位宽 = width + padding + border

八、
node.appendChild(node)
node.insertBefore(newnode,existingnode)
node.removeChild(node)
node.replaceChild(newnode,oldnode) node为oldnode的父节点
这几个函数既能操作已有的节点,也能操作动态创建的节点(createElement())
node.insertBefore(newnode,existingnode)当existingnode当null时在ie下会报错解决的方式就是:用if判断如果为null执行什么操作,否则执行什么操作。

简单的留言板:<!DOCTYPE html><html><head>    <meta charset="UTF-8"></head><body>    <input type="text" name="text" id="text" />    <input type="button" name="btn" id="btn" value="添加" />    <ul id="ul1">    </ul>    <script type="text/javascript">        var text = document.getElementById(&#39;text&#39;);        var btn = document.getElementById(&#39;btn&#39;);        var oul = document.getElementById(&#39;ul1&#39;);

        btn.onclick =function(){            var li = document.createElement(&#39;li&#39;);
            li.innerHTML = text.value;            var oa = document.createElement(&#39;a&#39;);
            oa.innerHTML = &#39;删除&#39;;
            oa.href = &#39;javascript:;&#39;;
            oa.onclick = function(){
                oul.removeChild(this.parentNode);
            }
            li.appendChild(oa);            if(!oul.children[0]){
                oul.appendChild(li);
            }else{
                oul.insertBefore(li,oul.children[0]);
            }            if(oul.children.length>5){
                oul.removeChild(oul.children[oul.children.length-1])
            }
        }    </script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
Copy after login

The above is the detailed content of Detailed explanation of DOM attribute methods and compatibility issues. 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