Liondancer
Liondancer

Reputation: 16469

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

Upvotes: 1

Views: 67

Answers (2)

Jason Nichols
Jason Nichols

Reputation: 3760

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

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

JavaScript Arrays don't have the method .getElementsByTagName

Upvotes: 2

PrakashSharma
PrakashSharma

Reputation: 386

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>

Upvotes: 2

Related Questions