原生JS封装查找父元素节点的方法
// 需要传递两个参数 一个 是 要查找父节点的子元素 另一个是要查找的父元素的层级
function retParent(ele,n){
while(ele&&n){
ele = ele.parentElement;
n--
}
return ele
}
image.png
原生JS封装查找兄弟元素节点的方法
function retSibling(ele,n){
while(ele&&n){
if(n>0){
if(ele.nextElementSibling){
ele = ele.nextElementSibling;
}else{
for(ele=ele.nextSibling;ele&&ele.nodeType!=1;ele=ele.nextSibling);
//ele.nodeType==1ie9一下判定是否为元素节点
}
n--;
}else{
if(ele.previousElementSibling){
ele = ele.previousElementSibling;
}else{
for(ele=ele.previousSibling;ele&&ele.nodeType!=1;ele=ele.previousSibling);
};
n++;
}
}
return ele;
}
var strong = document.getElementsByTagName("strong")[0];
var sib = retSibling(strong,2);
sib.style.color="red"
插入子节点方法
<div>
<span>12</span>
<p>2</p>
<div>divsiv
<strong>strong</strong>
</div>
<i>i</i>
<address>address</address>
</div>
var div = document.getElementsByTagName("div")[0];
var span = document.getElementsByTagName("span")[0];
var i = document.createElement("i");
var p = document.createElement("p");
div.insertBefore(i,span)
div.appendChild(p)
删除节点
<div>
<span>12</span>
<p>2</p>
<div>divsiv
<strong>strong</strong>
</div>
<i>i</i>
<address>address</address>
</div>
var div = document.getElementsByTagName("div")[0];
var span = document.getElementsByTagName("span")[0];
var i = document.getElementsByTagName("i")[0];
var spanDel = div.removeChild(span);//返回span 相当于事剪切掉了;
i.remove()//彻底消失了 ie不兼容 innerHTML innerText都兼容较好
设置 / 获取 属性
<div>
<span>12</span>
<p>2</p>
<strong>strong</strong>
<i>i</i>
<address>address</address>
</div>
var div = document.getElementsByTagName("div")[0];
var span = document.getElementsByTagName("span")[0];
var i = document.getElementsByTagName("i")[0];
div.setAttribute("id","div1")
div.getAttribute("id")
div.setAttribute("data-id","id1")//设置系统没有的属性
给元素批量添加自定义属性
<div>
<span>12</span>
<p>2</p>
<strong>strong</strong>
<i>i</i>
<address>address</address>
</div>
var div = document.getElementsByTagName("div")[0];
var eles = div.getElementsByTagName("*");
var span = document.getElementsByTagName("span")[0];
var i = document.getElementsByTagName("i")[0];
for(var i=0;i<eles.length;i++){
eles[i].setAttribute("this-name",eles[i].nodeName);
}
编写js脚本生成DOM结构;//全兼容
var body = document.body;
var div = document.createElement("div");
var p = document.createElement("p");
//div.setAttribute("class","example");
div.className="example";//可以更改
p.setAttribute("class","slogan");
p.innerHTML = "我最帅";
div.appendChild(p);
body.appendChild(div);
网友评论