J22 操作DOM

139 阅读2分钟

1.JS中常用的DOM操作

DOM:document Object model 文档对象模型(提供一系列的属性和方法,供我们获取和操作DOM元素)

1.获取DOM的方式
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>操作DOM</title>
	<link rel="stylesheet" href="reset.min.css">
	<style>
	 .active{
		 color:red;
		 background-color:pink;
	 }
	</style>
</head>

<body>
	<div class="box">
	    <h2>新闻标题</h2>
		<ul id="itemBox" class="item" >
			<li class='noLine' >我是第一条新闻</li>
			<li>我是第二条新闻</li>
			<li  class='noLine'>我是第三条新闻</li>
			<li>我是第四条新闻</li>
			<li>我是第五条新闻</li>		
		</ul>
	</div>
	<div class="noLine" name='node'>我是外面的div</div>
	<input type="text" name="node" id="">
</body>
</html>

1.获取一个对象:getElementById

let itemBox=document.getElementById("itemBox");
console.dir(itemBox);  //=>ul#itemBox.item
//因为它是一个对象,所以我们才可以item.xxx=xxx;

2.获取一个集合:getElementsByTagName

navList=itemBox.getElementsByTagName('li');
console.dir(navList);//=>HTMLCollection(5)
//它是一个元素集合HTMLCollection(类数组集合,数字作为索引,length代表长度)

3.获取整个页面中所有具备noLine样式类的元素:getElementsByClassName

//获取到的结果是元素集合,不管集合中有几项,它都是集合
let noLines=document.getElementsByClassName('noLine');
console.log(noLines);//=>[li,li,div]

let item=document.getElementsByClassName('item');
item=item[0];//=>获取集合中的第一项(这才是我们要操作的元素item对象)
console.log(item);//=>ul#itemBox.item

let noLines=item.getElementsByClassName('noLine');
console.log(noLines);//=>[li.noLine, li.noLine]

4.xxx.getElementsByName:表单都是这样子的方式获取的

let nodes=document.getElementsByName('node');
console.log(nodes);//=>NodeList(2) [div.node, input]

5.获取 item这个ul:getElementById

//方法一
let itemBox=document.getElementById('itemBox');
console.log(itemBox);//=> <ul id='itemBox' class='item></ul>'

//方法二
let ul=document.getElementsByTagName("ul")[0];
console.log(ul);//=> <ul id='itemBox' class='item></ul>'

//方法三
let item=document.getElementsByClassName('item')[0];
console.log(item);//=><ul id='itemBox' class='item></ul>'

6.querySelector不管匹配的结果有多少个,都只获得第一个元素对象

let itemBox=document.querySelector('ul');
console.log(itemBox);//=><ul id='itemBox' class='item></ul>'

7.querySelectorAll获取的都是集合(哪怕只有一项也是集合)

let navList=document.querySelectorAll('#itemBox li');
console.log(navList);//=>[li.noLine, li, li.noLine, li, li]
2.修改样式类

1.设置行内样式01

let itemBox=document.getElementById("itemBox");
itemBox.style.color='red';
itemBox.style.background='pink';
//=><ul id="itemBox" class="item" style="color: red; background: pink;">

2.设置行内样式:这种方式是style一个设置样式的简写,批量给行内上设置很多样式

let itemBox=document.getElementById("itemBox");
itemBox.style.cssText=`color:red;background-color:pink`;

3.使用内嵌式:给.active写一个样式

let itemBox=document.getElementById("itemBox");
//3-1.这样子可以 记得加空格区分每个样式类
itemBox.className+= ' active';

//3-2.向指定样式集合中新增一个样式类(兼容性差)
itemBox.classList.add("active");

// 3-3 这样子操作不可以
itemBox.className='active';//=className这样操作会吧之前的