先简单设置布局调试使用
<div class="father"><div class="son1">son1文本</div><button class="son2">son2文本</button><p class="son3">son3文本</p><input type="text" class="son4" placeholder="son4文本"></div>
var father = document.querySelector(".father")var son1 = document.querySelector(".son1")var son2 = document.querySelector(".son2")var son3 = document.querySelector(".son3")var son4 = document.querySelector(".son4")
子节点
console.log(father.children); //HTMLCollection:返回所有子元素console.log(father.children[0]); //返回索引为0的子元素
console.log(father.childNodes[0]); //返回索引为0的子元素console.log(father.childNodes); // Nodelist:返回所有元素节点
childNodes多了文本节点text, 是因为xml会把换行符当做文本节点来处理,所以才会有#text的出现)
(属性带有Element的方法一般是对元素节点的操作)
childElementCount: 返回子元素( 不包括文本节点和注释) 的个数
console.log(father.childElementCount); //4
firstChild 第一个子节点
console.log(father.firstChild) //#text
firstElementChild第一个子元素
console.log(father.firstElementChild) //son1
lastChild 最后一个子节点
console.log(father.lastChild) //#text
lastElementChild最后一个子元素节点
console.log(father.lastElementChild) //son4
父节点
parentElement 和 parentNode: 获取父元素
(不同之处: parentNode用法中, html的父元素为document.而parentElement 为undfined)
console.log(son1.parentElement) //father
同胞节点
nextSibling 获取下一个兄弟节点
console.Sibling) //#text
nextElementSibling 获取下一个兄弟元素节点
console.ElementSibling) //son2
previousSibling 获取上一个兄弟节点
console.log(son2.previousSibling); //#text
previousElementSibling获取上一个兄弟元素节点
console.log(son2.previousElementSibling); //son1
node节点属性
nodeName: 获取的是节点的类型名称
console.deName); //div
nodeType: 获取节点类型,返回的是数字: 元素1 属性2 文本3 注释8 文档9
son3.childNodes[0]返回的是"son3" ,而son3.children[0]返回的是undefined
console.log(deType); //undefinedconsole.log(son3.childNodes[0].nodeType); //3 为文本console.log(son3.attributes[0].nodeType); //2 为属性
nodeValue: 获取节点值是节点的值。其中属性节点和文本节点是有值的,而文档节点和元素节点没有值。
console.log(deValue) //undefinedconsole.log(deValue); //undefinedconsole.log(son3.childNodes[0].nodeValue) //返回文本内容:son3文本console.log(son3.attributes[0].nodeValue); //返回属性:son3
attributes 返回属性值
console.log(son3.attributes); //返回NamedNodeMap对象内容console.log(son3.attributes[0]); //class="son3"
innerHTML: 获取元素内容
console.log(son3.innerHTML) //son文本 会渲染html标签console.log(son3.innerText); //son文本 只是单纯文本
获取所有的同胞元素
function getSiblings(ele) {var slibings = []//cs等于这个父元素的所有子元素var cs = ele.parentElement.children//a为父元素的子元素长度var a = cs.lengthfor (var i = 0; i < a; i++) {//如果这个元素不等于 索引所在的子元素if (ele != cs[i]) {//则将它加入到数组slibings.push(cs[i])}}return slibings}console.log(getSiblings(son1)); //son2 son3 son4
返回指定索引的元素节点
//返回指定元素的子元素节点 father.a = function(index) {//如果这个索引值>这个元素的数量则返回nullif (index > this.childElementCount) {return null}return this.children[index - 1]}console.log(father.a(2)); //son2
本文发布于:2024-02-03 04:21:58,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170690531648619.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |