firstElementChild&&firstChild

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="box">
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
</div>
<script type="text/javascript">
var oBox = document.getElementById("box");
//alert(oBox.firstChild.nodeType);
//alert(oBox.firstElementChild.nodeType);

// if(oBox.firstElementChild){
// oBox.firstElementChild.style.background = 'red';
// }else{
// oBox.firstChild.style.background = 'red';
// }

var FC = oBox.firstElementChild ||oBox.firstChild;
FC.style.background = 'red';
oBox.children[0].style.background = 'red';

oBox.lastChild.style.background = 'red';
oBox.lastElementChild.style.background = 'red';
oBox.children[oBox.children.length-1].style.background = 'red'
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/zzgyq/p/6529298.html