1 <!-- HTML结构 -->
2 <div id="test-div">
3 <div class="c-red">
4 <p id="test-p">JavaScript</p>
5 <p>Java</p>
6 </div>
7 <div class="c-red c-green">
8 <p>Python</p>
9 <p>Ruby</p>
10 <p>Swift</p>
11 </div>
12 <div class="c-green">
13 <p>Scheme</p>
14 <p>Haskell</p>
15 </div>
16 </div>
第一种方法:
- // 选择<p>JavaScript</p>:
- //var js = document.getElementById('test-p');
- // 选择<p>Python</p>,<p>Ruby</p>,<p>Swift</p>:
- //var arr = document.getElementsByClassName('c-red c-green')[0].children;
- // 选择<p>Haskell</p>:
- //var haskell = document.getElementsByClassName('c-green')[1].lastElementChild;
第二种方法:
- var js = document.querySelector('#test-p');
- var arr = document.querySelectorAll('#test-div > .c-red.c-green > p');
- var haskell = document.querySelectorAll('#test-div > .c-green > p')[4];
第三种方法:
- // 选择<p>JavaScript</p>: var js = document.getElementById('test-p');
- // 选择<p>Python</p>,<p>Ruby</p>,<p>Swift</p>: var arr = document.querySelectorAll('.c-red.c-green>p');
- // 选择<p>Haskell</p>: var haskell = document.getElementById('test-div').lastElementChild.lastElementChild;