简体   繁体   中英

Grabbing inner html tags with Javascript

I am trying to get the objects for the inner <li> for this html. The one with the id=config_#

  <li class="browser_list">
    <ul>
      <li id="config_3"> Chrome 29</li>
      <li id="config_4"> Chrome 31</li>
      <li id="config_5"> Chrome 33</li>
      <li id="config_6"> Chrome 35</li>
    </ul>
  </li>
  <li class="browser_list">
    <ul>
      <li id="config_1">Firefox 11</li>
      <li id="config_2">Firefox 15</li>
    </ul>
  </li>
  <li class="browser_list">
    <ul>
      <li id="config_0">Internet Explorer 8</li>
    </ul>
  </li>

My code:

var list = document.getElementsByClassName("browser_list");
console.log(list);

for (var i = 0; i < list.length; i++) {
    var items = list.getElementsByTagName("li");
    console.log(items);
}

console.log(list) works fine but when I try to getElementsByTagName("li") I get the error:

Uncaught TypeError: undefined is not a function

I feel as though I am missing something but as I am new to JS I am not sure what it is

list is an array. Each element of the array is an HTMLElement

you'd need to use list[i].getElementsByTagName

JavaScript Array s don't have the method .getElementsByTagName

The getElementByClassName creates an array as more than 1 browser_list are found. So access it proper index.

 var list = document.getElementsByClassName("browser_list"); console.log(list); for (var i = 0; i < list.length; i++) { var items = list[i].getElementsByTagName("li"); console.log(items); } 
  <li class="browser_list"> <ul> <li id="config_3"> Chrome 29</li> <li id="config_4"> Chrome 31</li> <li id="config_5"> Chrome 33</li> <li id="config_6"> Chrome 35</li> </ul> </li> <li class="browser_list"> <ul> <li id="config_1">Firefox 11</li> <li id="config_2">Firefox 15</li> </ul> </li> <li class="browser_list"> <ul> <li id="config_0">Internet Explorer 8</li> </ul> </li> 

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