有时候不需要使用jquery,而如果需要用原生js获取节点就比较麻烦了
以下是一些比较常用的api,记录一下。
不一定兼容ie
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
<div id="box">
<p>first</p>
<p>two</p>
<p>three</p>
<p>four</p>
<p>last</p>
</div>
</body>
</html>
<script type="text/javascript">
// 通过id获取节点
var dom0 = document.getElementById('box');
console.log(dom0);
// 也可以用querySelector
let dom = document.querySelector('#box');
console.log(dom);
// 获取到子节点
console.log('children', dom.children);
// firstChild会获取到换行(如果有)
console.log('firstChild', dom.firstChild);
// firstElementChild会去掉换行
console.log('firstElementChild', dom.firstElementChild);
console.log('children下标获取', dom.children[0].innerHTML);
// 获取紧挨着的同级元素
console.log('nextSibling', dom.children[0].nextSibling);
// nextElementSibling
console.log('nextElementSibling', dom.children[0].nextElementSibling);
</script>