Home  >  Article  >  Web Front-end  >  JavaScript learning summary [5] JS DOM

JavaScript learning summary [5] JS DOM

黄舟
黄舟Original
2017-02-09 16:43:27924browse

1. Introduction to DOM

When the page is loaded, the browser will create the Document Object Model of the page. The Document Object Model defines standard methods for accessing and processing HTML documents. The DOM presents an HTML document as a tree structure of elements, attributes, and text, known as a node tree. Through DOM, JS can create dynamic HTML, which can make web pages display dynamic effects and realize interactive functions with users. JS can change all HTML elements, attributes and CSS styles on the page and respond to all events on the page. Therefore, the starting point for learning JS is to process web pages. To process web pages, you need to use DOM for operations.

2. DOM acquisition element

If JS wants to operate an HTML element, it must first find the element. This is usually done using the following methods:

Find the HTML element through the id set by the element.

Find HTML elements by tag name.

Find the HTML element by the name set by the element.

The so-called DOM is actually document, and getting elements is to operate document.

 (1). Find the element by id

Method: document.getElementById('id');

Web pages combine information by tags, and the id attribute value It is unique, just like an ID card. The corresponding person can be found through an ID card, so through this method, the corresponding tag can be obtained, and the obtained element is an object in JS. If you want to To operate on an element, you need to use its properties or methods.

 (2). Find elements by tag name

Method: document.getElementsByTagName('Tagname');

Through this method, the returned element with the specified tag name A collection of objects, that is, returned in the form of an array, in the order they are returned in the document.

 (3). Find the element by name

Method: document.getElementsByName('name');

This method is somewhat similar to the getElementById() method, both are passed The element is found by setting the attribute value, but this method finds the element by setting the name attribute value. The name attribute may not be unique in the document, so this method returns an array of elements instead of a single element.

<body>
 <input name="txt" type="text" value="1">
 <input name="txt" type="text" value="2"><br>
 <input name="txt" type="text" value="3">
 <input name="txt" type="text" value="4"><br>
 <input name="txt" type="text" value="5">
 <input name="aaa" type="text" value="6">
 <script> //获取所有name值为txt的元素
 var oTxt = document.getElementsByName("txt");  
 
 //获取元素的个数
 alert(oTxt.length);       //返回:5 
 //获取第二个元素的值
 alert(oTxt[1].value);    //返回:2
 </script>

Since elements can be found by id, elements can also be found by class. The className attribute is used to set or return the class name of the element.

Syntax: object.className = 'className'

This method can control the class name and return the class attribute of the element. Its function is to specify a className for an element in the web page to change it. The appearance of the element.

Example: Simple web page skin change effect

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>网页换肤</title>
 <style>
 body{
     background:lightgreen;
 }
 .col1{
     background:lightgray;
 }
 .col2{
     background:lightblue;
 }
 .col3{
     background:violet;
 }
 .col4{
     background:pink;
 }
 .col5{
      background:#f93;
 }
 </style>
 </head>
 <body id="boy">
 点击切换:<input type="button" value="灰色" onclick="gr()">
 <input type="button" value="蓝色" onclick="bl()">
 <input type="button" value="紫色" onclick="vi()">
 <input type="button" value="粉色" onclick="pi()">
 <input type="button" value="橘色" onclick="or()">
 <script>
 var x = document.getElementById(&#39;boy&#39;); function gr(){     x.className = &#39;col1&#39;; } 
 function bl(){     x.className = &#39;col2&#39;; } 
 function vi(){     x.className = &#39;col3&#39;; } 
 function pi(){     x.className = &#39;col4&#39;; } 
 function or(){     x.className = &#39;col5&#39;; } </script>
 </body>
 </html>

This is just a simple background color switching effect. If you want to switch the overall style of the web page, you can use an external CSS file and change the link tag through JS. href attribute to complete.

If you want to set the style of multiple elements with the same class name, you need to use the array method to complete it. The implementation principle is also very simple. First, get its parent element through the id, and then get all the elements under the parent element. The tag name of the child element. Obtaining the tag name returns an array of elements, so you can access the array of elements in the same way as accessing the array. Then use a loop to traverse the array of elements first, and then make a judgment. If the className of this element is equal to The class attribute value we set indicates that this is the element we are looking for.

Example: Set the background color of all elements in the ordered list whose class attribute value is "col" to green

 <body>
 <ol id="o1">
     <li>热点</li>
     <li class="col">美食</li>
     <li>数码</li>
     <li class="col">科技</li>
     <li>社会</li>
     <li class="col">养生</li>
 </ol>
 <script> //通过id获取父元素
 var aOl = document.getElementById(&#39;o1&#39;); //通过标签名获取父元素下所有子元素
 var oLi = aOl.getElementsByTagName(&#39;li&#39;); //循环遍历返回的子元素数组
 for(var i=0; i<oLi.length; i++){     //如果当前子元素的className等于设置的class属性值,则将其背景设置为绿色
     if(oLi[i].className == &#39;col&#39;) oLi[i].style.background = &#39;green&#39;; } </script>
 </body>

The following is a package function that obtains elements through the class attribute value, which is convenient for the future use.

 <!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>封装getByClass函数</title>
 <script>
  //第一个参数为获取的父元素,第二个参数为class属性值。
  function getByClass(oParent,aClass){     //空数组可以把找到的所有className都存放在里边,最后返回。
     var aResult = [];     //通过标签名获取父元素下所有子元素。标签名不固定,所以设置为*,便于传入。
     var aEle = oParent.getElementsByTagName(&#39;*&#39;);     //循环遍历返回的子元素数组
     for(var i=0; i<aEle.length; i++){         //如果当前子元素的className等于传入的class属性值,则将其添加到数值中。
         if(aEle[i].className == aClass) aResult.push(aEle[i]);     }     //最后将这个数组返回
     return aResult; } </script>
 </head>
 <body>
 <ol id="o1">
     <li>热点</li>
     <li class="col">美食</li>
     <li>数码</li>
     <li class="col">科技</li>
     <li>社会</li>
     <li class="col">养生</li>
  </ol>
 <script>
 //封装函数的使用:
 //先通过id获取父元素
 var aOl = document.getElementById(&#39;o1&#39;); //再调用封装好的函数传入参数,获取的父元素,子元素的class属性值
 var oCol = getByClass(aOl,&#39;col&#39;); //最后循环遍历,设置样式
 for(var i=0; i<oCol.length; i++){     oCol[i].style.background = &#39;green&#39;; } </script>
 </body>
 </html>

3. DOM operation

After obtaining the HTML element, you can perform the corresponding operation.

 (1). Change HTML

The simplest way to modify HTML content is to use the innerHTML attribute. innerHTML As the name suggests, inner is internal. Since it is HTML, you can put HTML inside. This property can be used to get and replace the content of an HTML element.

Syntax: document.getElementById(id).innerHTML = new HTML

<body>
 <h1 id="tit">原标题</h1>
 <script> //改变原有标题
 var aH = document.getElementById(&#39;tit&#39;); aH.innerHTML = &#39;新标题&#39;; </script>
 
 <div id="div1" style="width:500px;height:200px;border:1px solid black;"></div>
 <script> //创建HTML内容
 var oDiv = document.getElementById(&#39;div1&#39;); oDiv.innerHTML = &#39;<h2>我是h2标题</h2><p>我是一个段落</p>&#39;; </script>
 </body>

(2) Operating element attributes

The simplest way to modify element attributes is to modify them directly. Syntax: document.getElementById(id).Attribute name = new value For example, modify the pointing path of the image src attribute.

In addition, you can also obtain, add, and delete element attributes through DOM methods.

 ①、getAttribute()

The getAttribute() method obtains the value of the attribute through the attribute name of the element node.

Syntax: elementNode.getAttribute(name) name is the attribute name of the element node you want to get

②, setAttribute()

The setAttribute() method adds a new attribute and specify a value, or set an existing property to the specified value.

Syntax: elementNode.setAttribute(name,value) name is the attribute name and value is the attribute value.

 ③、removeAttribute()

The removeAttribute() method can delete the attributes of the element.

Syntax: elementNode.removeAttribute(name) name is the attribute name.

 <!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 </head>
 <body>
 <input id="txt1" type="text">
 <input id="btn1" type="button" value="按钮">
 <script>
 var oTxt = document.getElementById(&#39;txt1&#39;); var oBtn = document.getElementById(&#39;btn1&#39;); 
 //获取按钮value属性的值
 var a = oBtn.getAttribute(&#39;value&#39;); alert(a);    //返回:按钮
 
 oBtn.onclick = function (){     //操作元素属性有三种方法:
     //第一种方法
     //oTxt.value=&#39;请输入文字&#39;;
 
     //第二种方法
     //oTxt[&#39;value&#39;]=&#39;请输入文字&#39;;
 
     //第三种方法
     //修改文本框value属性的值
     oTxt.setAttribute(&#39;value&#39;,&#39;请输入文字&#39;); 
     //删除按钮type属性
     oBtn.removeAttribute(&#39;type&#39;);     //删除后默认为文本框
 }; </script>
 </body>
 </html>

 (3)、Change CSS

  改变 HTML 元素的 CSS 样式可直接使用该语法:document.getElementById(id).style.样式名 = new style

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 <style>
 #div1{
     height:400px;
     width:600px;
     border:1px solid black;
     padding:5px;
 }
 p{
     line-height:18px;
     text-indent:2em;
 }
 </style>
 </head>
 <body>
 <h2>HTML DOM</h2>
 <div id="div1">
     <h3>JS可以使网页添加动态效果并实现与用户交互的功能。</h3>
     <p>1. JS能够改变页面中所有的 HTML 元素。</p>
     <p>2. JS能够改变页面中所有的 HTML 属性。</p>
     <p>3. JS能够改变页面中所有的 HTML 元素的CSS样式。</p>
 </div>
 
 <input type="button" value="改变颜色" onclick="color()">
 <input type="button" value="改变宽高" onclick="hig()">
 <input type="button" value="隐藏内容" onclick="none()">
 <input type="button" value="显示内容" onclick="block()">
 <input type="button" value="取消设置" onclick="cancel()">
 
 <script>
 var oDiv = document.getElementById(&#39;div1&#39;); 
 function color(){     
 oDiv.style.color = &#39;white&#39;;     
 oDiv.style.fontFamily = &#39;Microsoft YaHei&#39;;     
 oDiv.style.backgroundColor = &#39;green&#39;; } 
 function hig(){     oDiv.style.width = &#39;400px&#39;;     
 oDiv.style.height = &#39;300px&#39;;     
 oDiv.style.border = &#39;5px solid #ccc&#39;; } 
 function none(){     oDiv.style.display = &#39;none&#39;; } 
 function block(){     oDiv.style.display = &#39;block&#39;; } 
 //取消设置
 function cancel(){     var clean = confirm(&#39;确定取消所有设置?&#39;);     
 if(clean == true){         oDiv.removeAttribute(&#39;style&#39;);     } } </script>
 </body>
 </html>

上面的代码,通过 style 设置的样式,都是行间样式,可以使用火狐的 Firebug 点击相应的按钮,就能看到所有设置的 CSS 样式都出现在了行间。

  可以直接通过 style 获取和设置 CSS 样式,那么有没有更简洁的方法呢?可以借助于函数使用 JS 的内置对象 arguments 完成,所谓 arguments,就是可变参,不定参,参数的个数可变,是一个参数数组,无需指出参数名,就可访问他们,但是为了增强可读性,给参数取名,还是很有必要的。

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 </head>
 <body>
 <div id="div1" style="width:200px;height:200px;background:red"></div>
 <script>
 //获取行间样式
 function css(){     //如果传入参数的个数等于2
     if(arguments.length == 2){         //则返回第二个参数样式名的值
         return arguments[0].style[arguments[1]];     }     else{         //否则就是设置CSS样式
         //第二个参数样式名的值就等于传入的第三个参数
         arguments[0].style[arguments[1]] = arguments[2];     } } 
 var oDiv = document.getElementById(&#39;div1&#39;); alert(css(oDiv,&#39;width&#39;));    //获取对象的宽 返回:200px
 css(oDiv,&#39;background&#39;,&#39;green&#39;);    //将对象的背景颜色改为绿色
 </script>
 </body>
 </html>

  下面是一个获取和设置行间样式的封装函数,以便以后使用。

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>获取行间样式</title>
 <script>
 function css(obj, name, value){     if(arguments.length == 2){         return obj.style[name];     }     else{         obj.style[name] = value;     } } </script>
 </head>
 <body>
 <div id="div1" style="width:200px;height:200px;background:red"></div>
 <script>
 var oDiv = document.getElementById(&#39;div1&#39;); alert(css(oDiv,&#39;width&#39;));    //获取div的宽
 css(oDiv,&#39;background&#39;,&#39;green&#39;);    //设置div的背景颜色
 </script>
 </body>
 </html>

我们都知道,在实际的 Web 项目开发中,要遵循结果、表现、行为相分离的原则,以增强可读性,优化代码,便于后期维护。所以通常我们设置元素的样式,并非都是在行间设置。使用 style 方法获取的只是 DOM 元素 style 属性里的样式规则,对于通过 class 属性设置的外部样式表,style 就显得力不从心了。那要如何获取元素的非行间样式呢?DOM 标准中有个全局方法 getComputedStyle,通过该方法可以获取当前对象的样式信息。比如:getComputedStyle(obj, false).paddingLeft,可以获取到对象的左内边距。这里需要注意:在获取元素的复合样式时,一定要使用精确的值,复合样式比如 background、border,如果要获取元素的背景颜色,只使用 background 会出错,一定要写成 backgroundColor。

  JS 只能修改元素的行间样式,并不能修改获取到的非行间样式。那么很多人可能会产生疑问,既然可以获取到又不能修改,那还获取有什么用。其实获取非行间样式是非常有必要的,如果是外部样式表,样式都是密密麻麻一片英文的存在,不可能一个个去找,到底该元素设置的什么样子,再回头修改,那岂不是太浪费精力了,所以该方法就显得尤为重要,而且返回的值都是精确值,通过获取的非行间样式信息,也有利于更精细的修改元素的当前样式,这是多么美妙的一件事,直接使用 style 设置元素的行间样式,因为行间样式的优先级最高,所以就覆盖掉了非行间样式,其实也就相当于跟修改了非行间样式一样,只是显示在了行间,我们目的反着是已经达到了。

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>获取非行间样式</title>
 <style>
 #div1{
     width:200px;
     height:200px;
     background:red;
     margin-top:10px;
 }
 </style>
 <script>
 window.onload = function (){     var oDiv = document.getElementById(&#39;div1&#39;); 
     alert(getComputedStyle(oDiv,false).width);     oDiv.style.width = &#39;400px&#39;; 
     alert(getComputedStyle(oDiv,false).height);     oDiv.style.height = &#39;400px&#39;; 
     //注意这里修改复合样式时,使用的background,可在FF下用Firebug查看具体的行间样式。
     alert(getComputedStyle(oDiv,false).backgroundColor);     oDiv.style.background = &#39;green&#39;; }; </script>
 </head>
 <body>
 <div id="div1"></div>
 </body>
 </html>

(4)、对事件做出响应

  实例:全选和反选,输入对应的序号选中

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 </head>
 <body>
 <form id="list">
     请选择你的业余爱好:<br>
     1. 音乐<input type="checkbox" name="love" id="like1">
     2. 阅读<input type="checkbox" name="love" id="like2">
     3. 游泳<input type="checkbox" name="love" id="like3">
     4. 篮球<input type="checkbox" name="love" id="like4">
     5. 足球<input type="checkbox" name="love" id="like5">
     6. 散步<input type="checkbox" name="love" id="like6">
     7. 泡吧<input type="checkbox" name="love" id="like7">
     8. 逛街<input type="checkbox" name="love" id="like8"><br>
     <input type="button" value = "全选" onclick="optAll()">
     <input type="button" value = "反选" onclick="noAll()">
 
     <p>输入1-8序号选择,每次只可以选择一项:</p>
     <input id="txt1" type="text">
     <input id="btn1" type="button" value="确定">
 </form>
 <script>
 function optAll(){     //通过获取标签名设置全选
     var oList = document.getElementById(&#39;list&#39;);     
     var aCheck = oList.getElementsByTagName(&#39;input&#39;);     
     for(var i=0; i<aCheck.length; i++){         
     if(aCheck[i].type == &#39;checkbox&#39;){             
     aCheck[i].checked = true;         }     } } 
 function noAll(){     //通过获取设置的name属性值设置反选
     var aLove = document.getElementsByName(&#39;love&#39;);  
     for(var i=0; i<aLove.length; i++){         
     if(aLove[i].type == &#39;checkbox&#39;){             
     aLove[i].checked = false;         }     } } 
 var oBtn = document.getElementById(&#39;btn1&#39;); //给获取的按钮添加点击事件
 oBtn.onclick = function (){     //获取文本框输入的值
     var oTxt = document.getElementById("txt1").value;     //定义的复选框id值为like1-8。括号中进行的是字符串连接,id+输入到文本框的值=该元素的id值
     var oLike = document.getElementById(&#39;like&#39; + oTxt);     
     oLike.checked = true; } </script>
 </body>
 </html>

3、DOM节点

  HTML 文档可以说是由节点构成的集合,常见的 DOM 节点有三种,即元素节点、属性节点和文本节点。元素节点就是 HTML 标签,标签的属性就是属性节点,文本节点就是页面可以浏览的内容。

  在文档对象模型中,每一个节点都是一个对象,DOM 节点有三个重要的属性:节点的名称,节点的值和节点的类型。

  (1)、nodeName:节点的名称

  nodeName 属性返回节点的名称。元素节点的名称与标签名相同(大写),属性节点的名称是属性的名称,文本节点的名称永远都是 #text,文档节点的名称永远都是 #document。

  (2)、nodeValue:节点的值

  nodeValue 属性返回节点的值。元素节点的值是 undegined 或 null,属性节点的值是属性的值,文本节点的值是文本自身。

  (3)、nodeType:节点的类型

  nodeType 属性返回节点的类型。以下是常见的节点类型:

JavaScript learning summary [5] JS DOM

 <body>
 <ul>
     <li>JS</li>
     <li>DOM</li>
 </ul>
 <script>
 var nodes = document.getElementsByTagName(&#39;li&#39;); 
 for(var i=0; i<nodes.length; i++){     
 document.write(&#39;第&#39; + (i+1) + &#39;个节点的名称是&#39; + nodes[i].nodeName + &#39;<br>&#39;);     
 document.write(&#39;第&#39; + (i+1) + &#39;个节点的值是&#39; + nodes[i].nodeValue + &#39;<br>&#39;);     
 document.write(&#39;第&#39; + (i+1) + &#39;个节点的类型是&#39; + nodes[i].nodeType + &#39;<br>&#39;);     
 document.write(&#39;<br>&#39;); } 
 
 /*
 返回: 第1个节点的名称是LI 第1个节点的值是null 第1个节点的类型是1 
 第2个节点的名称是LI 第2个节点的值是null 第2个节点的类型是1 */
 </script>
 </body>

JS 中函数可以嵌套使用,有父函数有子函数,HTML 标签也可以嵌套使用,那么就说明存在着各种不同的节点关系,比如父节点、子节点和兄弟节点。为了方便操作,DOM定义了一些节点的公共属性。

  (1)、子节点

  childNodes 属性返回节点的子节点集合,可使用length属性返回子节点的数量,然后就可以和数组一样获取需要的信息。

 <body>
 <ul id="u1">
     <li>1</li>
     <li>2</li>
     <li>3</li>
     <li>4</li>
     <li>5</li>
 </ul>
 <script>
 var oUl = document.getElementById(&#39;u1&#39;); alert(oUl.childNodes.length);    //返回:11
 </script>
 </body>

通过上面的代码,可以看到返回的是 11。ul 下明明只有 5 个 li 元素,怎么会返回 11 呢?其实是这么回事:

<ul id="u1">   第1个节点(文本节点)     
<li>第2个节点(元素节点)</li> 第3个节点(文本节点)     
<li>第4个节点(元素节点)</li> 第5个节点(文本节点)     
<li>第6个节点(元素节点)</li> 第7个节点(文本节点)     
<li>第8个节点(元素节点)</li> 第9个节点(文本节点)     
<li>第10个节点(元素节点)</li> 第11个节点(文本节点) 
</ul>

因为通过 childNodes 属性返回的子节点集合,不仅包括元素节点,而且还包括文本节点,浏览器会将标签之间的空白默认为文本节点,如果在空白处输入文字,就会显示在页面上,这就造成了不必要的麻烦,所以建议使用 children 属性,该属性只返回元素节点,不包括文本节点,并且不包括注释节点。

 <body>
 <ul id="u1">
     <li>
         我是个文本节点         <span>我是span元素。</span>
     </li>
     <li></li>    <!-- 注释 -->
     <li></li>
     <li></li>
     <li></li>
 </ul>
 <script>
 var oUl = document.getElementById(&#39;u1&#39;); alert(oUl.children.length);    //返回:5
 </script>
 </body>

  上面的代码,ul 下有 5 个 li 元素,返回子节点个数为 5。children 属性要比 childNodes 属性好用太多了,只返回元素的子节点,还不包括孙子辈节点。

  (2)、首尾子节点

  firstElementChild 属性返回 children 数组的第一个节点。

  语法:node.firstElementChild  该方法相当于:element.children[0]

 

  lastElementChild 属性返回 children 数组的最后一个节点。

  语法:node.lastElementChild  该方法相当于:element.children[element.children.length-1]

<body>
 <div style="border:2px solid green" id="div1">
    空白节点   <p>JS</p>
   <div>DOM</div>
   <h3>jQuery</h3>
 </div>
 <script>
 var x = document.getElementById(&#39;div1&#39;); 
 document.write(&#39;第一个节点的名称:&#39; + x.firstElementChild.nodeName + &#39;<br>&#39;); //返回:第一个子节点的名称:P
 document.write(&#39;最后一个节点的名称:&#39; + x.lastElementChild.nodeName) //返回:最后一个子节点的名称:H3
 </script>
 </body>

 (3)、父节点

  parentNode 属性用于获取指定节点的父节点。注意:父节点只能有一个。通过使用两个获取父节点,可获取祖节点。

  实例:点击子节点,隐藏父节点

 <!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 </head>
 <body>
 <ul id="u1">
     <li>aaa <a href="javascript:;">点击隐藏</a></li>
     <li>bbb <a href="javascript:;">点击隐藏</a></li>
     <li>ccc <a href="javascript:;">点击隐藏</a></li>
     <li>ddd <a href="javascript:;">点击隐藏</a></li>
     <li>eee <a href="javascript:;">点击隐藏</a></li>
 </ul>
 <script>
 var oUl = document.getElementById(&#39;u1&#39;); //查看ul元素的父节点
 alert(oUl.parentNode);    //返回:[object HTMLBodyElement]
 
 //通过标签名获取所有的a元素
 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>
 </body>
 </html>

  offsetParent 属性可返回一个元素用于定位的父级。

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 <style>
 #div1{
     width:200px;
     height:200px;
     background:green;
     margin:100px;
     /*position:relative;*/
 }
 #div2{
     width:100px;
     height:100px;
     background:red;
     position:absolute;
     left:50px;
     top:50px;
 }
 </style>
 </head>
 <body>
 <div id="div1">
     <div id="div2"></div>
 </div>
 <script>
 var oDiv2 = document.getElementById(&#39;div2&#39;); alert(oDiv2.offsetParent); //返回:[object HTMLBodyElement]
 
 //div2的父级是div1,如果取消div1相对定位的注释。则返回:[object HTMLDivElement]
 </script>
 </body>
 </html>

(3)、兄弟节点

  nextElementSibling 属性返回同一树层级中某个节点之后紧跟的节点。

  语法:element.nextElementSibling  

 

  previousElementSibling 属性返回同一树层级中某个节点之前紧跟的节点。

  语法:element.previousElementSibling

 

  实例:获取 li 元素节点的兄弟节点

 <body>
 <ul>   
     <li>HTML</li>   
     <li>CSS</li>
     <li>JS</li>   
 </ul>     
 <script>
 var aLi = document.getElementsByTagName(&#39;li&#39;); //获取第二个子节点之后紧跟的节点
 var x = aLi[1].nextElementSibling; alert(x.innerHTML);    //返回:JS
 
 //获取第二个子节点之前紧跟的节点
 var y = aLi[1].previousElementSibling; alert(y.innerHTML);    //返回:HTML
 </script>
 </body>

4、DOM 应用

  DOM 最实际的应用就是可以通过 JS 创建、插入和删除节点。

  (1)、创建节点

  createElement() 方法可创建元素节点。

  语法:document.createElement(tagName)

 

  appendChild()方法可在指定节点的末尾插入一个新的子节点,每次都向末尾添加。

  语法:父级.appendChild(new node)

 

  实例:创建并添加 li 元素

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 <script>
 window.onload = function (){     
 var oBtn = document.getElementById(&#39;btn1&#39;);     
 var oUl = document.getElementById(&#39;u1&#39;);     
 var oTxt = document.getElementById(&#39;txt1&#39;); 
     //文本框输入提示
     oTxt.placeholder = &#39;请输入文字创建li元素&#39;; 
     oBtn.onclick = function (){         //创建li元素
         var oLi = document.createElement(&#39;li&#39;); 
         //创建的li元素的HTML=文本框输入的值
         oLi.innerHTML = oTxt.value; 
         //插入到oUl父级下,作为子节点,在每个创建的li末尾插入新创建的li元素
         oUl.appendChild(oLi);         //父级.appendCild(子节点);
     }; }; </script>
 </head>
 <body>
 <input id="txt1" type="text"value="">
 <input id="btn1" type="button"value="创建li">
 <ul id="u1"></ul>
 </body>
 </html>

(2)、插入节点

  insertBefore() 方法可在已有的子节点前插入一个新的子节点。

  语法:父级.insertBefore(new node, node)  第一个参数为要插入的新子节点。第二个参数是原有节点,也就是在谁之前插入。

  实例:创建并添加 li 元素,每个新创建的 li 元素都插入到之前插入的 li 元素之前

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 <script>
 window.onload = function (){   
   var oBtn = document.getElementById(&#39;btn1&#39;);     
 var oUl = document.getElementById(&#39;u1&#39;);    
  var oTxt = document.getElementById(&#39;txt1&#39;); 
     oBtn.onclick = function (){         //创建li元素
         var oLi = document.createElement(&#39;li&#39;);         //获取所有li元素
         var aLi = oUl.getElementsByTagName(&#39;li&#39;);         oLi.innerHTML = oTxt.value; 
         //这里需要注意:页面中本没有li元素,li元素是通过JS创建的
         //所以第一个li元素应该添加到父级下最后一个子节点
         //然后基于这个节点,将之后再插入的子节点插入到上一个节点之前
 
         //如果li元素本来不存在,则执行else,在父级插入一个子节点。
         //如果li元素的个数>0,说明已经创建了,则插入到这个子节点之前。
         if(aLi.length>0){             
         oUl.insertBefore(oLi,aLi[0]);         
         }         
         else{             
         oUl.appendChild(oLi);        
          }     
          }; };
           </script>
 </head>
 
 <body>
 <input id="txt1" type="text" value="">
 <input id="btn1" type="button" value="创建li">
 <ul id="u1"></ul>
 </body>
 </html>

 (4)、删除节点

  removeChild() 方法用于删除一个节点

  语法:父级.removeChild(node)  参数为要删除的子节点。

  实例:简单的表格添加和删除

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 <script>
 window.onload = function (){     
 var oTab = document.getElementById(&#39;tab1&#39;);     
 var oName = document.getElementById(&#39;user&#39;);     
 var oAge = document.getElementById(&#39;age&#39;);     
 var oBtn = document.getElementById(&#39;btn1&#39;);     
     //设置添加的ID项的值
     var id = oTab.tBodies[0].rows.length+1; 
     oBtn.onclick = function (){         //创建一个tr
         var oTr = document.createElement(&#39;tr&#39;);         //创建第一个td(ID项)
         var oTd = document.createElement(&#39;td&#39;);         //获取ID,已经删除的ID号,不能再重用。
         oTd.innerHTML = id++;         //将创建的td放入创建的tr中
         oTr.appendChild(oTd); 
         //创建第二个td(姓名项)
         var oTd = document.createElement(&#39;td&#39;);         
         oTd.innerHTML = oName.value;         
         oTr.appendChild(oTd); 
         //创建第三个td(年龄项)
         var oTd = document.createElement(&#39;td&#39;);        
          oTd.innerHTML = oAge.value;        
           oTr.appendChild(oTd); 
         //创建第四个td(操作项)
         var oTd = document.createElement(&#39;td&#39;);         
         oTd.innerHTML = &#39;<a href="javascript:;">删除</a>&#39;;         
         oTr.appendChild(oTd); 
         oTd.getElementsByTagName(&#39;a&#39;)[0].onclick = function (){             //删除整行
             oTab.tBodies[0].removeChild(this.parentNode.parentNode);         }; 
         //将创建好的tr放入tbody中
         oTab.tBodies[0].appendChild(oTr);     }; }; </script>
 </head>
 <body>
 姓名:<input id="user"type="text">
 年龄:<input id="age"type="text">
 <input id="btn1" type="button" value="添加">
 <table id="tab1" border="1" width="500px">
     <caption>员工表</caption>
     <thead>
         <tr>
             <th>ID</th>
             <th>姓名</th>
             <th>年龄</th>
             <th>操作</th>
         </tr>
     </thead>
     <tbody>
         <tr>
             <td>1</td>
             <td>小白</td>
             <td>27</td>
             <td></td>
         </tr>
         <tr>
             <td>2</td>
             <td>小明</td>
             <td>25</td>
             <td></td>
         </tr>
         <tr>
             <td>3</td>
             <td>小红</td>
             <td>21</td>
             <td></td>
         </tr>
         <tr>
             <td>4</td>
             <td>张三</td>
             <td>29</td>
             <td></td>
         </tr>
         <tr>
             <td>5</td>
             <td>李四</td>
             <td>35</td>
             <td></td>
         </tr>
     </tbody>
 </table>
 </body>
 </html>

这个实例只能很简单的完成添加和删除,并不对输入进行判断,如果想要做的完美,还需要做很多工作,可以对表格进行美化,设置背景色,鼠标移入高亮显示,鼠标移出恢复背景色,最关键的就是要对表单输入内容进行判断,以确保每次提交的信息都是有效信息,如果表格信息量大,还可以添加支持模糊搜素,多关键字搜索,以提高用户体验度,当然在实际的项目中,这样的情况几乎不会出现,但可以作为自己的实践,检验学习成果。

  (5)、替换节点和创建文本节点

  replaceChild() 方法可用于替换元素节点。

  语法:node.replaceChild (new node, node)  第一个参数为用于替换的节点。第二个参数为原有节点。

 

  createTextNode() 方法可创建新的文本节点,返回新创建的 Text 节点。

  语法:document.createTextNode(txt)

  这两种方法平时几乎用不到,但还是需要了解。

  实例:点击按钮将 span 标签替换为 b 标签。再创建一个文本节点插入到创建的 p 元素下,并设置 className

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="UTF-8">
     <title>JavaScript实例</title>
 <style>
 .p1{
     width:300px;
     height:100px;
     background-color:#ccc;
 }    
 </style>
 </head>
 <body>
 <p>创建一个P标签,设置<span id="s">className</span>属性,创建文本节点。</p>
 <input type="button" value="点击替换" onclick="change()">
 <script>
 function change(){     //获取span元素
     var oS = document.getElementById(&#39;s&#39;);     //创建一个b元素
     var newNode = document.createElement(&#39;b&#39;);     //要替换的文本节点
     var txt = document.createTextNode(&#39;className&#39;);     //将文本节点插入到创建的b元素下
     newNode.appendChild(txt);     //在span元素的父级下将span元素替换成新创建的b元素
     oS.parentNode.replaceChild(newNode,oS); } 
 //创建一个p元素
 var oP = document.createElement(&#39;p&#39;); //设置className
 oP.className = &#39;p1&#39;; //创建文本节点
 var txtNode = document.createTextNode(&#39;createTextNode用于创建文本节点!&#39;); //将创建的文本节点插入到p元素下
 oP.appendChild(txtNode); //再将p元素插入到父级body下
 document.body.appendChild(oP); </script> 
 </body>
 </html>

以上就是 JavaScript学习总结【5】JS DOM的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
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