简体   繁体   中英

How can I access list values using DOM in javascript?

I want an array (or simple string values, if not an array) containing values in <ul> . My code is below :

<!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>

The values I get alerted are either undefined or [object text], while I want an array so I can access them using array[0] or something like that.

Do with querySelectorAll()

 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> 

For Nodelist array creation with li text and forEach() iterate the array .Then push textContent to array 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM