[英]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.