Dom中的查

Dom中的查###

1.通过元素间的关系####

1)父子关系

parentElement 查找一个元素的父元素


console.log(why.parentElement)
 //查找id为why的父元素

why.parentElement.style.backgroundColor='#ff0';
 //设置why父元素的背景色

children 查找父元素的所有子元素 找到多个


console.log(why.children);
 //查找id为why的所有子元素(结果为数组形式)
why.children[3].style.color='#f00';
//给ceshi的子元素中下标为3的设字体颜色

firstElementChild 找到父元素下的第一个子元素

···js

console.log(why.firstElementChild.children[0].firstElementChild);

var li=why.firstElementChild.children[0].firstElementChild;
li.style.color='red';

lastElementChild   找到父元素下的最后一个子元素

```js

console.log(why.firstElementChild.children[0].lastElementChild);

var li=why.firstElementChild.children[0].lastElementChild;
li.style.color='#fff';

2)兄弟关系

previousElementSibling 前一个兄弟
nextElementSibling 下一个兄弟


var who=why.firstElementChild.nextElementSibling.children[0].firstElementChild.nextElementSibling;
console.log(who);
who.style.backgroundColor='#00f';

var who=why.children[2].previousElementSibling.firstElementChilwho.lastElementChild;
console.log(who);
who.style.color='#ff0';

2.通过HTML查找####

1)通过id查找


//var ele=document.getElementById('id号');// 只能找到一个

var id=document.getElementById('why');
console.log(id);
id.style.backgroundColor='#f0f';

2)通过class查找


//var ele=document.getElementsByClassName('class名');
//特点:可以找到多个  并且返回一个动态集合(数组)

var king=document.getElementsByClassName('king');
console.log(king);
king[0].style.backgroundColor='#ff0';

3)通过标签名


//var ele=document.getElementsByTagName('标签名');
//特点:可以找到多个  返回动态集合 (数组)

var li=document.getElementsByTagName('li');
console.log(li);
for(var i=0;i

4)通过name属性查找


//var  ele=document.getElementsByName('name');
//可以找到多个  返回动态集合  数组

var uname=document.getElementsByName('uname');
console.log(uname);

3.通过选择器查找####


//var ele=document.querySelector('选择器'); // 只能找到一个
var who=document.querySelector('#why>li>ul>li:first-child');
console.log(who);
who.style.color='#f0f';

//var ele=document.querySelectorAll('选择器');// 查找所有   返回动态集合  (数组)

var arr=document.querySelectorAll('#why>li:nth-child(2)>ul>li');
console.log(arr);
for(var i=0;i

你可能感兴趣的:(Dom中的查)