Jeevan Jose Jeevan Jose - 5 days ago 5
Javascript Question

Why does chrome throw 'getAttribute' is not a function error inside a for loop?

With the following markup:

<div id="parent">
<div id="one">one</div>
<div id="two">two</div>
<div id="three">three</div>
<div id="four">four</div>
<div id="five">five</div>
<div id="six">six</div>
</div>

<p id="output">

</p>


and the following javascript:

var output = document.getElementById('output');
var items = document.querySelectorAll('#parent > div');

output.innerHTML += '#' + items[2].getAttribute('id') + '<br /><br />';

for(index in items){
output.innerHTML += '#' + items[index].getAttribute('id') + ': ';
output.innerHTML += items[index].innerHTML + '<br />';
}


Chrome throws the following error in the console:


Uncaught TypeError: items[index].getAttribute is not a function


I have checked this in IE 11 and there are no errors in the console. What's weird is that the actual result of the expression is correct.

Does anyone know why this is happening?



var output = document.getElementById('output');
var items = document.querySelectorAll('#parent > div');

output.innerHTML += '#' + items[2].getAttribute('id') + '<br /><br />';

for(index in items){
output.innerHTML += '#' + items[index].getAttribute('id') + ': ';
output.innerHTML += items[index].innerHTML + '<br />';
}

#output{
color: blue;
}

<div id="parent">
<div id="one">one</div>
<div id="two">two</div>
<div id="three">three</div>
<div id="four">four</div>
<div id="five">five</div>
<div id="six">six</div>
</div>

<p id="output">

</p>




A.J A.J
Answer

To get id you need to do [DOMNode].id :

Working Snippet:

var output = document.getElementById('output');
var items = document.querySelectorAll('#parent > div');

output.innerHTML += '#' + items[2].id + '<br /><br />';

for (index in items) {
  output.innerHTML += '#' + items[index].id + ': ';
  output.innerHTML += items[index].innerHTML + '<br />';
}
<div id="parent">
  <div id="one">one</div>
  <div id="two">two</div>
  <div id="three">three</div>
  <div id="four">four</div>
  <div id="five">five</div>
  <div id="six">six</div>
</div>

<p id="output">

</p>

Comments