


Detailed explanation of DOM attribute methods and compatibility issues
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):
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('ul1'); alert(ul.id); /*标准与非标准都是div1*/ alert(ul.index);/*标准为undefined 非标准为hehe*/ </script> </body></html>123456789101112131415161718192021
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('ul1'); alert(oul.childNodes.length);</script>在标准浏览器下:得到的结果为5(li元素前的换行空文本,li元素,注释到</li>之间这一段文本,注释,注释到</ul>的空白) 在非标准的浏览器下得到的结果为1 但是将<li>22222</li> 111111互换位置之后得到的结果为2.1234567891011
所以当运行下面代码的时候为出问题:<!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('ul1'); for(var i = 0; i<oul.childNodes.length; i++){ oul.childNodes[i].style.backgroundColor = 'red'; } /*标准: Cannot set property 'backgroundColor' of undefined*/ /*非标准:(ie8之前)正常*/ </script> </body></html>原因很简单,就是因为在标准浏览器下childNodes返回的子节点中包含非元素类型的节点。12345678910111213141516171819202122232425
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 = 'red'; }1234
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('ul1'); for(var i = 0; i<oul.childNodes.length; i++){ if(oul.childNodes[i].nodeType === 1) oul.childNodes[i].style.backgroundColor = 'red'; } </script> </body> </html>1234567891011121314151617181920212223
对于一些分标准的浏览器比如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('ul1'); alert(oul.firstChild.nodeName); /*标准下text非标准为li*/ </script></body></html>123456789101112131415161718192021
解决这种情况
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 = 'orange'; }else{ alert('没有第一个元素'); }123456789101112131415
2直接用children:推荐
if(oul.children[0]){ oul.children[0].style.backgroundColor = 'orange'; }else{ alert('没有第一个元素'); }123456
四、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('a'); for (var i=0; i<aA.length; i++) { aA[i].onclick = function() { this.parentNode.style.display = 'none'; } } }</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
五、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('div3'); alert( oDiv3.offsetParent.id ); }</script></head><body id="body1"> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div></body></html>1234567891011121314151617181920212223242526272829
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('div3'); alert( oDiv3.offsetTop ); }</script></head><body id="body1"> <div id="div1"> <div id="div2"> <div id="div3"></div> </div> </div></body></html>123456789101112131415161718192021222324252627
例子:获得任意一个元素的相对 于页面的位置<!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('div3'); 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
七、长高:
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('text'); var btn = document.getElementById('btn'); var oul = document.getElementById('ul1'); btn.onclick =function(){ var li = document.createElement('li'); li.innerHTML = text.value; var oa = document.createElement('a'); oa.innerHTML = '删除'; oa.href = 'javascript:;'; 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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Nowadays, many mobile phones claim to support Bluetooth 5.3 version, so what is the difference between Bluetooth 5.3 and 5.2? In fact, they are essentially subsequent updated versions of Bluetooth 5, and there is not much difference in most performance and functions. The difference between Bluetooth 5.3 and 5.2: 1. Data rate 1 and 5.3 can support higher data rates up to 2Mbps. 2. While 5.2 can only reach a maximum of 1Mbps, it means that 5.3 can transmit data faster and more stably. 2. Encryption control enhancement 2. Bluetooth 5.3 improves encryption key length control options, improves security, and can better connect to access control and other devices. 3. At the same time, because the administrator control is simpler, the connection can be more convenient and faster, which is not possible in 5.2.

The performance of i77700 is completely sufficient to run win11, but users find that their i77700 cannot be upgraded to win11. This is mainly due to restrictions imposed by Microsoft, so they can install it as long as they skip this restriction. i77700 cannot be upgraded to win11: 1. Because Microsoft limits the CPU version. 2. Only the eighth generation and above versions of Intel can directly upgrade to win11. 3. As the 7th generation, i77700 cannot meet the upgrade needs of win11. 4. However, i77700 is completely capable of using win11 smoothly in terms of performance. 5. So you can use the win11 direct installation system of this site. 6. After the download is complete, right-click the file and "load" it. 7. Double-click to run the "One-click

Methods for setting browser compatibility include selecting appropriate HTML and CSS standards, using CSS prefixes and resets, using browser compatibility prefix libraries, detecting browser features, using browser compatibility tools, and conducting cross-browser testing. Detailed introduction: 1. Choose appropriate HTML and CSS standards. When writing HTML and CSS codes, you should try to follow W3C standards. Different browsers will have different support for standards, but following standards can maximize compatibility. sex; 2. Use CSS prefixes, etc.

The Go language has very good compatibility on Linux systems. It can run seamlessly on various Linux distributions and supports processors of different architectures. This article will introduce the compatibility of Go language on Linux systems and demonstrate its powerful applicability through specific code examples. 1. Install the Go language environment. Installing the Go language environment on a Linux system is very simple. You only need to download the corresponding Go binary package and set the relevant environment variables. Following are the steps to install Go language on Ubuntu system:

More and more users are starting to upgrade the win11 system. Since each user has different usage habits, many users are still using the ie11 browser. So what should I do if the win11 system cannot use the ie browser? Does windows11 still support ie11? Let’s take a look at the solution. Solution to the problem that win11 cannot use the ie11 browser 1. First, right-click the start menu and select "Command Prompt (Administrator)" to open it. 2. After opening, directly enter "Netshwinsockreset" and press Enter to confirm. 3. After confirmation, enter "netshadvfirewallreset&rdqu

With the continuous development of modern technology, wireless Bluetooth headsets have become an indispensable part of people's daily lives. The emergence of wireless headphones frees our hands, allowing us to enjoy music, calls and other entertainment activities more freely. However, when we fly, we are often asked to put our phones in airplane mode. So the question is, can I use Bluetooth headphones in airplane mode? In this article, we will explore this question. First, let’s understand what airplane mode does and means. Airplane mode is a special mode for mobile phones

The software in the win10 system has been perfectly optimized, but for the latest win11 users, everyone must be curious about whether this system can be supported, so the following is a detailed introduction to the win11 software that does not support win10. Come and find out together. Does win11 support win10 software: 1. Win10 system software and even Win7 system applications are well compatible. 2. According to feedback from experts who use the Win11 system, there are currently no application incompatibility issues. 3. So you can upgrade boldly with confidence, but ordinary users are advised to wait until the official version of Win11 is released before upgrading. 4. Win11 not only has good compatibility, but also has Windo

1. Right-click the program and find that the [Compatibility] tab is not found in the properties window that opens. 2. On the Win10 desktop, right-click the Start button in the lower left corner of the desktop and select the [Run] menu item in the pop-up menu. 3. The Win10 run window will open, enter gpedit.msc in the window, and then click the OK button. 4. The Local Group Policy Editor window will open. In the window, click the [Computer Configuration/Administrative Templates/Windows Components] menu item. 5. In the opened Windows component menu, find the [Application Compatibility] menu item, and then find the [Remove Program Compatibility Property Page] setting item in the right window. 6. Right-click the setting item, and in the pop-up menu
