Reputation: 361
Why do I output an array length of 0? It's making my loop not work and my understanding of this code not clear.
<!DOCTYPE html>
<html>
<head>
<title>My Awsome Website</title>
</head>
<body>
<h1>My list</h1>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<script>
var list = document.getElementsByTagName('<li>');
document.write(list.length);
/*
for (var i = 0; i < list.length; i++) {
list[i].style.backgroundColor = 'red';
list[i].style.color = 'white';
}
*/
</script>
</body>
</html>
Upvotes: 2
Views: 172
Reputation: 498914
There are no elements with tag name <li>
.
There are several with tag name li
, though.
The line should be:
var list = document.getElementsByTagName('li');
Upvotes: 10
Reputation: 10030
var list = document.getElementsByTagName('li');
use above. That getElementsByTagName
has only one param which is the tag name of the required element.
Upvotes: 5