1、第一次做:
// 选择<p>JavaScript</p>:
var js = document.getElementById('test-p');
//document.getElemensByClassName('c-red').firstChild;
//document.getElemensByClassName('c-red')[0];
// 选择<p>Python</p>,<p>Ruby</p>,<p>Swift</p>:
var arr = document.getElemensByClassName('c-red c-green');
// 选择<p>Haskell</p>:
var haskell = document.getElemensByClassName('c-green').lastChild;
//document.getElemensByClassName('c-green')[1];
2、
练习
如下的HTML结构:
JavaScript
Java
Python
Ruby
Swift
Scheme
Haskell
<!-- HTML结构 -->
<div id="test-div">
<div class="c-red">
<p id="test-p">JavaScript</p>
<p>Java</p>
</div>
<div class="c-red c-green">
<p>Python</p>
<p>Ruby</p>
<p>Swift</p>
</div>
<div class="c-green">
<p>Scheme</p>
<p>Haskell</p>
</div>
</div>```
请选择出指定条件的节点:
'use strict';
// 选择<p>JavaScript</p>:
//var js = document.getElementById('test-p');
var js = document.querySelector('#test-p');
// 选择<p>Python</p>,<p>Ruby</p>,<p>Swift</p>:
//var arr = document.getElementsByClassName('c-red c-green')[0].getElementsByTagName('p');
var arr =document.querySelectorAll('div.c-red.c-green > p');
// 选择<p>Haskell</p>:
var haskell = document.getElementsByClassName('c-green')[1].getElementsByTagName('p')[1];
var haskell = document.querySelectorAll('c-green')[1].lastElementChild;
// 测试:
if (!js || js.innerText !== 'JavaScript') {
alert('选择JavaScript失败!');
} else if (!arr || arr.length !== 3 || !arr[0] || !arr[1] || !arr[2] || arr[0].innerText !== 'Python' || arr[1].innerText !== 'Ruby' || arr[2].innerText !== 'Swift') {
alert('选择Python,Ruby,Swift失败!');
} else if (!haskell || haskell.innerText !== 'Haskell') {
alert('选择Haskell失败!');
} else {
alert('测试通过!');
}