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

In-depth JavaScript DOM application

php中世界最好的语言
Release: 2018-03-13 13:29:34
Original
1410 people have browsed it

This time I will bring you in-depth JavaScript DOM application, What are the precautions when using JavaScript DOM application, the following is a practical case, let's take a look.

What is DOM:
Document, node! In fact, it is all about the same thing. In CSS, it is called a label, in JS, it is called an element, and in DOM, it is called a node;

Browser support
IE:10% Chrome:60% FF:99% Support

DOM node
childNodes: child node
nodeType: type of node

nodeType == 3 -> Text node

nodeType == 1 -> Element node

childNodes and nodeType are used together

<head>    <meta charset="UTF-8">
    <title>01-DOM基础</title>
    <script>
        window.onload = function () {            //        ul的子节点为li
            var oUl = document.getElementById(&#39;ul1&#39;);            for(var i=0;i<oUl.childNodes.length;i++){                //由于在不同的浏览器下,获取到的oUl.childNodes是不一样的;IE6-8会将文本节点也算进去;
                //故若想给元素节点修改样式,可以通过 oUl.childNodes[i].nodeType == 1 来获取元素节点,并修改样式;
                //nodeType==3   ->  文本节点
                //nodeType==1   ->  元素节点
                //给所有的li设置背景颜色
                if(oUl.childNodes[i].nodeType == 1){
                    oUl.childNodes[i].style.background = &#39;red&#39;;
                }
            }
        }    </script></head><body><ul id="ul1">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li></ul>abcdefg //文本节点<span>abcdefg</span> //元素节点</body></html>
Copy after login

Get child nodes
children:he Only includes elements, no text, compatible with all browsers
So the above example can be written like this, simple and crude!!!

for (var i=0;i<oUl.children.length;i++){
     oUl.children[i].style.background = &#39;red&#39;;
}
Copy after login

parentNode: parent node
Example: click on the link to hide the entire li
parentNode example:

<html lang="en"><head>
    <meta charset="UTF-8">
    <title>02-parentNode</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>
    <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>
Copy after login

offsetParent
Example: Get the actual position of the element on the page
Mainly used for positioning, get the actual parent node of the element.

Example One: Set absolute positioning to the second div2, and set nothing to the parent node div1 of div2, then the offsetParent of div2 is body.

<html lang="en"> <head>     <meta charset="UTF-8">     <title>offsetParent</title>     <style>         #div1{width: 200px;height: 200px;background: #ccc;margin-left: 100px;}         #div2{width: 100px;height: 100px;background: red;position: absolute;left: 10px;}     </style>     <script>         window.onload = function () {             oDiv2 = document.getElementById(&#39;div2&#39;);             alert(oDiv2.offsetParent); //结果:[object HTMLBodyElement] 父节点为body;         }     </script> </head> <body> <div id="div1">     <div id="div2"></div> </div> </body> </html>
Copy after login

Example 2: Give the second div2 Set absolute positioning and set relative positioning for the parent node div1 of div2, then the offsetParent of div2 is div1.

<html lang="en"> <head>     <meta charset="UTF-8">     <title>offsetParent</title>     <style>         #div1{width: 200px;height: 200px;background: #ccc;margin-left: 100px;             position: relative;}         #div2{width: 100px;height: 100px;background: red;position: absolute;left: 10px;}     </style>     <script>         window.onload = function () {             oDiv2 = document.getElementById(&#39;div2&#39;);             alert(oDiv2.offsetParent); //结果:[object HTMLDivElement] 父节点为div;         }     </script> </head> <body> <div id="div1">     <div id="div2"></div> </div> </body> </html>
Copy after login

2.DOM node (2)

First and last child node

There are compatibility issues

firstChild、firstElementChild
lastChild 、lastElementChild
   //IE6-8    //oUl.firstChild.style.background=&#39;red&#39;;    //高级浏览器    //oUl.firstElementChild.style.background=&#39;red&#39;;
Copy after login

Usage examples

<html><head><meta charset="utf-8"><title>无标题文档</title><script>window.onload=function (){    var oUl=document.getElementById(&#39;ul1&#39;);    //IE6-8
    //oUl.firstChild.style.background=&#39;red&#39;;
    //高级浏览器
    //oUl.firstElementChild.style.background=&#39;red&#39;;
    //给第一个li设置红色背景:由于兼容问题,故需判断下
    if(oUl.firstElementChild)
    {
        oUl.firstElementChild.style.background=&#39;red&#39;;
    }    else
    {
        oUl.firstChild.style.background=&#39;red&#39;;
    }
};</script></head><body><ul id="ul1">
    <li>1</li>
    <li>2</li>
    <li>3</li></ul></body></html>
Copy after login

Sibling nodes (use the same as above)

There are compatibility issues

nextSibling, nextElementSibling

previousSibling, previousElementSibling

3. Manipulate element attributes

ElementAttribute operation
First type: oDiv.style.display=' block';
Second type: oDiv.style['display']='block';
Third type: Dom method: oDiv2.setAttribute('display','none');

DOM way to operate element attributes
Get: getAttribute(name)
Set: setAttribute(name, value)
Delete: removeAttribute(name)

4. Use className to select the element

How to select elements using className

Select all elements

Filter by className conditions
Basic usage

<html><head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <script>
        window.onload=function ()        {            var oUl=document.getElementById(&#39;ul1&#39;);            var aLi=oUl.getElementsByTagName(&#39;li&#39;);            for(var i=0;i<aLi.length;i++)
            {                if(aLi[i].className==&#39;box&#39;)
                {
                    aLi[i].style.background=&#39;red&#39;;
                }
            }
        };    </script></head><body><ul id="ul1">
    <li class="box"></li>
    <li class="box"></li>
    <li></li>
    <li></li>
    <li></li>
    <li class="box"></li>
    <li></li></ul></body></html>
Copy after login

Encapsulate into a function
Advanced usage

   <script>
         //封装成函数
        function getByClass(oParent, sClass)        {            var aResult=[];            var aEle=oParent.getElementsByTagName(&#39;*&#39;);//*通配符,获取oParent下面所有的节点
            for(var i=0;i<aEle.length;i++)
            {                if(aEle[i].className==sClass)
                {
                    aResult.push(aEle[i]);
                }
            }            return aResult;
        }        window.onload=function ()        {            var oUl=document.getElementById(&#39;ul1&#39;);            var aBox=getByClass(oUl, &#39;box&#39;);            for(var i=0;i<aBox.length;i++)
            {
                aBox[i].style.background=&#39;red&#39;;
            }
        };    </script>
    <body>
       <ul id="ul1">
          <li class="box"></li>
          <li class="box"></li>
          <li></li>
          <li></li>
          <li></li>
         <li class="box"></li>
         <li></li>
       </ul></body>
Copy after login

5. Create, insert and delete elements

Create DOM elements
createElement(tag name) Create a node appendChild(node) Append a node

Note: appendChild (Node) has two functions:

(1) If this element is created through createElement (tag name), then it can be added directly to the new parent;
(2). If This element has a parent, then 1. Delete the element from the original parent first; 2. Add it to the new parent.

Example: Insert li for ul

<html><head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <script>
        window.onload=function ()        {            var oBtn=document.getElementById(&#39;btn1&#39;);            var oUl=document.getElementById(&#39;ul1&#39;);            var oTxt=document.getElementById(&#39;txt1&#39;);
            oBtn.onclick=function ()            {                //创建节点
                var oLi=document.createElement(&#39;li&#39;);
                oLi.innerHTML=oTxt.value;                //添加节点 父级.appendChild(子节点);
                oUl.appendChild(oLi);
            };
        };    </script></head><body><input id="txt1" type="text"/><input id="btn1" type="button" value="创建li"/><ul id="ul1"></ul></body></html>
Copy after login

Believe After reading the case in this article, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

In-depth basic application of JavaScript

##8 basic knowledge that must be paid attention to in JS

The above is the detailed content of In-depth JavaScript DOM application. 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