<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="fn()">按钮</button>
<div id="box" class="box section">box</div>
<script>
var div = document.querySelector('#box')
function fn () {
// div.id = 'box1'
// div.className = 'box2' // 这种写法是box2把原来的box直接覆盖
// div.className = 'box box2'
// div.className += ' box2'
// classList仅支持IE8+
// 添加一个class
// div.classList.add('ac')
// 移出一个class,如果要移出多个,那就分两次写
div.classList.remove('section')
console.log(div.className)
console.log(div.classList)
console.log(div.classList[0])
console.log(div.classList[1])
}
</script>
</body>
</html>
JS中获取网页元素id和class的操作
最新推荐文章于 2024-03-23 18:34:55 发布
本文详细讲解了JavaScript如何获取网页中具有特定id和class的元素,包括使用getElementById、getElementsByClassName等方法,帮助开发者更高效地操纵DOM。
1327

被折叠的 条评论
为什么被折叠?



