js怎樣獲取元素節點 怎樣獲取某個元素下的第一個節點 獲取相鄰的兄弟節點

有時候不需要使用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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章