![](/img/trans.png)
[英]How can i use Javascript to access an array of hyperlinks in a HTML doc using Legacy Dom and W3C Dom?
[英]How can I access list values using DOM in javascript?
我想要一個包含<ul>
中的值的數組(或簡單的字符串值,如果不是數組)。 我的代碼如下:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Unordered List with Disc Bullets</h2>
<ul style="list-style-type:disc">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<button onclick="changeColor()">Change</button>
<script type="text/javascript">
function changeColor(){
var a=document.childNodes[1].childNodes[2].childNodes[3];
alert(a.childNodes[0]);
}
</script>
</body>
</html>
我收到警報的值是未定義的或[對象文本],而我想要一個數組,所以我可以使用array [0]或類似的東西訪問它們。
function changeColor() { var a = document.querySelectorAll('ul li') console.log(a[0].innerHTML); }
<h2>Unordered List with Disc Bullets</h2> <ul style="list-style-type:disc"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> <button onclick="changeColor()">Change</button>
對於使用li text和forEach()
創建Nodelist數組,迭代數組。然后將textContent推送到數組arr
function changeColor() { var arr=[]; document.querySelectorAll('ul li').forEach(function(a){ arr.push(a.textContent) }) console.log(arr); }
<h2>Unordered List with Disc Bullets</h2> <ul style="list-style-type:disc"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> <button onclick="changeColor()">Change</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.