1.DOM元素查询
代码块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>dom的查询</title>
</head>
<body>
<form action="" id="login">
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
</ul>
<input type="text" data-my-age='16' name="" placeholder="123" id="hello"><button id="">提交</button>
</form>
<script>
let $ = (selector) => document.querySelector(selector);
//元素的查询
console.log(document.querySelectorAll('.item'));
//元素的遍历
const items = document.querySelectorAll('.item');
items.forEach(function (item, index, items) {
console.log(item, index, items)
})
//获取第一个元素
console.log("<hr>")
console.log( document.querySelector('.item'))
//元素的遍历
for (let item of items) {
console.log(item)
}
console.log(document.forms.login);
// 所有子节点包括文本节点
console.log(document.querySelector(".list").childNodes)
//只包括元素节点
console.log(document.querySelector(".list").children)
let eles = document.querySelector(".list").children;
let firstItem = eles[0];
firstItem.style.background = 'red';
secondItem = firstItem.nextElementSibling;
secondItem.style.background = 'green';
let prive = secondItem.previousElementSibling;
prive.style.background = "yellow";
// 自定义属性的查询
let input = document.querySelector("input");
console.log(input.dataset.myAge);
</script>
</body>
</html>
效果图
2.DOM元素的修改增加和删除
代码块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
let div = document.createElement("div");
let span = document.createElement("span");
console.log(div,span);
span.textContent = "hello";
// 将span添加到div中
div.append(span, ' world');
console.log(div);
//document.body.append(div);
// 要想保留span,要克隆span
document.body.append(span.cloneNode(true),' world');
const ul = document.createElement("ul");
for (let i = 1; i <=5; i++ ) {
let li = document.createElement("li");
li.textContent = `item${i}`;
li.style.color = 'red';
ul.append(li);
}
document.body.append(ul);
let li = document.createElement("li");
li.textContent = "fisrt li";
li.style.color = "green";
//添加到头部
ul.prepend(li);
const three = document.querySelector("li:nth-of-type(4)");
three.style.background = "cyan";
three.before(li);
three.after(li);
//修改
three.replaceWith(li);
//删除元素
ul.querySelector(":first-of-type").remove();
// 在第一个元素之前插入
li = document.createElement("li");
li.textContent = 123;
ul.insertAdjacentElement("afterbegin",li);
// 插入到ul标签之前
ul.insertAdjacentElement("beforebegin",li);
// 作为字符串插入到子元素的最后
ul.insertAdjacentHTML('beforeEnd',"<li>321</li>");
</script>
</body>
</html>
效果图