专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 HTML中Dom节点操作详解

HTML中Dom节点操作详解

更新时间:2022-09-01 10:18:49 来源:星辉 浏览879次

Dom概念 Dom

HTML教程中大家会遇到Dom,Document Object模型是一套完整的操作文档的方法——Document——html,document中的对象,dom中的顶级对象,window中的对象,可以说是最好的。

Dom Node:构成整个html流程的所有步骤,相当于构成整个网页的所有标签、文本、属性、注释——构成网页的每一部分内容都被视为一个节点,而整个网页是由很多节点组成的。节点主要有:(标签、文本、属性、评论)/元素节点(标签),因为在实际操作中,元素节点比较重要,所以在获取或创建的时候一个节点,你通常对元素节点进行操作,比如注释节点,文本节点使用的相对较少。

Dom 树:简单来说,一棵 Dom 树是由很多节点组成的。在根节点 HTML 的基础上,其余节点都是子节点。构成树的数据结构是 Dom 树。

Dom节点操作

那么我们为什么要得到节点呢?节点能做什么呢?

1. 寻找元素

2.设置元素属性值

3.风格元素

4. 创建/删除元素

5.事件的触发

等一下。

所以节点是非常强大的。涉及的知识比较多,我简单总结一下节点的所有基本操作。

如何获取元素

      console.log(document)  // document
         console.log(document.documentElement) // Obtain html Label
         console.log(document.body)  // Obtain body Label
         console.log(document.head)  // Obtain head Label
         console.log(document.title) // Obtain title Label 
         // Obtained with id Labeled dom Method must be used document call getElementById
         console.log(document.getElementById('id'))  // adopt id 
         //getElementsByTagName This method can be used in addition to document In addition, element calls can be used
         console.log(document.getElementsByTagName('div'))     // By tag name 
         console.log(document.getElementsByClassName('.box'))  // adopt class Name acquisition
         console.log(document.getElementsByName('name'))       // adopt name Name to get
         console.log(document.querySelector('.box'))           // adopt css Selector to get
         console.log(document.querySelectorAll('div'))         // adopt css Selector to get all the labels 
         // Summary: Passed id  and name Get label can only be used document Called,By tag name,class Name, css Selectors can call methods from parent elements to get labels for child elements

节点类型 nodeType & 节点名称 nodeName & 节点值 nodeValue

要获取节点的类型和名称,值需要先获取对应的节点。这里是我的html标签。

节点主要是文本节点、评论节点、元素节点

   <div id="ids">
         <!-- dom Is Document Object Model -->
         <div class="box">text</div>
         <p>text</p>
         <div class="box" name="1"></div>
         Text Properties
     </div>
          var ids = document.getElementById('ids') 
          var nodes = ids.childNodes // Obtain ids All child nodes under
          console.log(nodes)    // Nodes is a list of collections of all child nodes under ids  
          console.log(nodes[0].nodeType)  // Text Node Type 3
          console.log(nodes[0].nodeName)  // Text Node Name  #text
          console.log(nodes[0].nodeValue) // Text node value is the text content and space is the text node 
          console.log(nodes[1].nodeType)  // Comment Node Type 8
          console.log(nodes[1].nodeName)  // Comment Node Name  #comment
         console.log(nodes[1].nodeValue) // Annotation Node Value Is Annotation Content 
         console.log(nodes[3].nodeType)  // Element Node Type 1
         console.log(nodes[3].nodeName)  // Element Node Name Uppercase Label Name
         console.log(nodes[3].nodeValue) // Element Node Value  null

节点的操作

同样,我用名为 ids 的 ID 编写的 div 标签演示了节点的工作方式

          var ids = document.querySelector('#ids') // Get parent element 
          console.log(ids.childNodes) // Obtain ids All child nodes under
          console.log(ids.children)  // Obtain ids All child element nodes under         
          console.log(ids.firstChild)  // Obtain ids First child node under
          console.log(ids.firstElementChild) // Obtain ids First child element node under                console.log(ids.lastChild) // Obtain ids Last child node under
         console.log(ids.lastElementChild) // Obtain ids Last child element node under 
         console.log(ids.nextSibling)  // Next sibling node
         console.log(ids.nextElementSibling)  //   Next sibling element node 
         console.log(ids.previousSibling)  // Get the last sibling node
         console.log(ids.previousElementSibling)  // Get the last sibling element node // Not only the same label, but also different labels 
         console.log(ids.parentNode)  // Get Parent Node
         console.log(ids.parentElement)  // Get parent element node

节点的增删查操作(重要)

节点操作 - 添加

1.创建元素节点:document.createElement(字符串的标签签名)

2.创建文本节点:document.createTextNode(Text)相当于创建一个文件节点对象,可以直接插入到任何想要的位置

3.追加:父容器.appendChild;在父容器末尾插入子元素

4.向标签添加文本:父容器.textContent ='你要添加的内容'

5.插入标签:父Container.insertBefore

6.复制元素:元素。使用新变量接收克隆节点(深度布尔)

克隆节点

Deep Boolean==false 浅拷贝只拷贝元素,不拷贝内容和子元素

深度布尔==真。Deep Copy 允许您复制元素及其内容,以及它们的子元素

         var div = document.createElement('div')  // Create labels
          document.body.appendChild(div)    // Place the div element at the end of the body tag  
          // Append: parent container.appendChild(Child Elements);  Insert child elements at the end of parent container
         var span = document.createElement('span')
          div1.appendChild(span)  // take span Labels on div In Label
          span.textContent = 'Hello'  
          // Insert label in div Insert a b Label to span Before Note
         var b = document.createElement('b')
         // Insert Writing Form One:
         div.insertBefore(b,span)
         // Insert Writing Form Two:
         div.insertBefore(b,div.lastElementChild) 
         // Create a text node: document.createTextNode("text") 
         // Place in div Of b In Label
         var text = document.createTextNode('I am a created text node')
         // Insert the created text node into the div Before the first element node in
         div.insertBefore(text,div.firstElementChild)
         console.log(div) 
         // Copy Element Elements.cloneNode(Depth Boolean)
         var b1 = b.cloneNode(false)   // Shallow copy
         var b2 = b.cloneNode(true)    // Deep copy
         console.log(b1,b2)

节点操作-删除

Element.remove(); * 元素本身被删除

页面标签.remove(); // 指从 DOM 树中删除

父容器.removeChild; 父容器删除子元素

快速清除所有子元素:element. 内部HTML = ''。

var b = document.createElement('b')
        document.body.appendChild(b)
        // Copy Element
        var b1 = b.cloneNode(false)
        var b2 = b.cloneNode(false)        
        b1.remove()  // delete b1 element
        var dl = document.createElement('dl')
        document.body.appendChild(dl)
        dl.appendChild(b2)
        dl.removeChild(b2)   // Delete and Repeat dl In b2 element
        // Note that this does not remove the clean need b2 = null
        document.body.appendChild(b2)   // This line of code proves b2 Not deleted clean, cache is still in progress
        b2 = null   // When b2 Assigned to null time b2 Is completely deleted clean, can no longer be called
        // document.body.appendChild(b2)  // b2 cannot be called here and an error has occurred  

节点操作 - 更改

父容器.replaceChild(新元素,要替换的元素)

         var input = document.createElement('input')  // Establish input Label
         var div = document.createElement('div')      // Establish div Label
         document.body.appendChild(div)      // take div Elements are inserted in body Tail of
         document.body.replaceChild(input,div)   // Replace Element

DOM元素(标签)属性的操作

DOM 元素概念

任何 DOM 元素都有两个属性,一个是对象属性,另一个是标签属性

1.调用标签上写的属性标签属性

2.任何DOM元素都是对象模型,可以自动添加和设置对象的属性和值

元素属性的DOM操作——添加、删除、更改检查

元素的属性 - 添加 - 元素。setAttribute(属性名,属性值)

如何添加单个属性:如表单的checked属性,设置时:属性名('checked','checked') or ('checked',')

注意:属性名称不能命名为驼背。通常它们通过区分两个词来命名:toggle-target。属性值不能大写,必须是字符串

         var div0 = document.createElement('div')
         document.body.appendChild(div0)
         div0.setAttribute('Slag glow','One Knife 999')  // Add attributes to elements
         div0.setAttribute('class','999')  // Attribute 2 
         // 2: Attributes of the element - Delete - element.removeAttribute(Property Name)         div0.removeAttribute('Slag glow')  // Remove Attribute Slag Glow 
         // 3: Attributes of the element - change - In fact, it is the operation of adding attributes. When attributes do not exist, they are added, when attributes exist, they are modified on the original basis.
         div0.setAttribute('class','666666') 
         // 4:Attributes of the element - Get (view) property values - element.getAttribute(Property Name)
         console.log(div0.getAttribute('class')) 
         // Expand Knowledge 1: DOM Elements are object models and object attributes are not displayed on labels(For example: a Labeled href Properties, img Of src attribute)
         // Extend 1 case:1: img.src = 'The address of the picture you want to put in'  2: a.href = 'The address of the picture you want to put in' 3: div.a = 10 - to div Add a property named a Value is 10
         // Extend 2: DOM All elements are object,So setting attributes is based on object attributes. When conflicting values of label attributes and object attributes are encountered, the value of object attributes is taken as the criterion.
         // Extend 2 cases:
         var ck=document.querySelector("input")
         ck.setAttribute("checked","")  // input Add Attributes checked ,input Set up checked When, is for true == Selected
         ck.checked=false  // When the label attribute value conflicts with the object attribute value, the object attribute value is taken as the criterion. checked Is for false == Trim White Space

元素节点样式的操作

         // 1: Label Style - increase
         // Method 1: Increase inline (note inline) style elements by adding attributes.setAttribute(Property Name,Attribute Value)
         var div0 = document.createElement('div')
         document.body.appendChild(div0)
         div0.setAttribute("style","width:50px;height:50px;background-color:red")
         // Method 2: - element.style.The style name you want to add = 'Style Value'
         div0.style.margin = '5px' 
         // 2: Tag Style Acquisition 
         console.log(div0.style.width)  // Only inline styles can be obtained, not internal and external styles
         // Universal Access: getComputedStyle(element)   Inside, outside and inside styles are available
         console.log( getComputedStyle(div0).width) 
         // 3 :Gets the rectangular bounding range of the element ( IE8 Only later)
         // Syntax: Element..getBoundingClientRect()   
         // IE Compatibility method: element.currentStyle.Style Properties
         var res = div0.getBoundingClientRect()
         console.log(res)
         // This method is also an object model with eight attributes, one for each of the following
         /*{
             width,  // offsetWidth
             height, // offsetHeight
             left,   // Distance from the leftmost window to the visible window
             top,    // Distance from the top to the visible window
             right,  // left+width Distance from the far right to the visible window
             bottom, // top+height  Distance from bottom to visible window
             x,      // left  Coordinate X-axis
             y       // top   Coordinate Y-axis
         }
         */

以上就是关于“HTML中Dom节点操作详解”的介绍,大家如果想了解更多相关知识,可以关注一下星辉Java星辉在线学习,里面的课程内容细致全面,很适合没有基础的小白学习,希望对大家能够有所帮助。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>