1.querySelector()方法,根据选择器的名称获取指定的dom元素。注意:如果选择器不唯一,返回的是第一个元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>div1</div>
<div class="two">div2</div>
<div id="three">div3</div>
<script>
// 这里是根据标签选择器获取元素
let div1 = document.querySelector('div')
console.log(div1);
// 这里是根据类选择器获取元素
let div2 = document.querySelector('.two')
console.log(div2);
// 这里是根据id选择器获取元素
let div3 = document.querySelector('#three')
console.log(div3);
</script>
</body>
</html>
2.querySelectorAll()方法,根据选择器的名称获取所有的dom元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>div1</div>
<div class="two">div2</div>
<div id="three">div3</div>
<script>
// 这里是根据标签选择器获取元素
let div1 = document.querySelectorAll('div')
div1.forEach(item=>{
console.log(item);
})
</script>
</body>
</html>
3.可以通过层次选择器获取dom元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="one">
<p>好好学习</p>
</div>
<script>
document.querySelector('.one>p').style.backgroundColor='red'
</script>
</body>
</html>
4.总结:css里面的选择器怎么写,这里获取元素时的选择器就可以怎么写。