2017-06-27 41 views
3
<body> 

<nav> 
    <ul> 
     <li><a href="index.html">Portfolio</a></li> 
     <li><a href="about.html">About</a></li> 
     <li><a href="contact.html">Contact</a></li> 
    </ul> 
</nav> 

<section> 
    <ul> 
     <li><a href="previous-page.html">Previous</a></li> 
     <li><a href="next-page.html">Next</a></li> 
    </ul> 
</section> 

</body> 

孩子的HTML元素我想選擇什麼<li>標籤是在<nav>元素,並把它們放到一個列表裏面,但不包括<li>標籤是在<section>選擇使用JavaScript

我試過這個代碼,但它選擇整個頁面上的所有列表元素:

let list = document.selectElementsByTagName('li') 

我只能用香草JS,不是jQuery的。

+0

可能的複製(https://stackoverflow.com/questions/6584333/queryselectorall-usage) –

+0

'selectElementsByTagName'無效。 .. – epascarello

回答

4

它實際上getElementsByTagName ......
但是你可以使用.querySelectorAll(),如:

let list = document.querySelectorAll('nav li') 

例子:

let list = document.querySelectorAll('nav li'); 
 
let list2 = document.querySelector('section ul'); // Use rather some ID man 
 

 
Array.from(list).forEach((el) => list2.append(el.cloneNode(true)));
section { 
 
    background: #eee; 
 
}
<nav> 
 
    <ul> 
 
    <li><a href="index.html">Portfolio</a></li> 
 
    <li><a href="about.html">About</a></li> 
 
    <li><a href="contact.html">Contact</a></li> 
 
    </ul> 
 
</nav> 
 

 
<section> 
 
    <ul> 
 
    <li><a href="previous-page.html">Previous</a></li> 
 
    <li><a href="next-page.html">Next</a></li> 
 
    </ul> 
 
</section>

0

我知道你想使用香草的JavaScript。但是,使用jQuery你可以做同樣的用更少的代碼:[queryselectorAll用法]的

let list = $('nav li'); 
+0

更少的代碼?整個jQuery庫不一定少代碼:)只是少打字;) –