August
August

Reputation: 1819

document.getElementsByClassName("...")[0] returning undefined

I have a simple list and want to select the first element.

<ul>
  <li class="first">Test</li>
  <li>Test</li>
</ul>

My js:

var list = document.getElementsByClassName("first")[0];
console.log(list);

But the console is saying undefined, why is that? How should this be done the proper way?

Upvotes: 0

Views: 1824

Answers (3)

shaik sha
shaik sha

Reputation: 1

<body>
<div class="fruits">Apple<div>
  <script src="javascript.js"></script>
</body>

it should be like this in a body close tag before put javascript

Upvotes: 0

Pavangowda S U
Pavangowda S U

Reputation: 76

Javascript Code is going to execute before the HTML code, so when the javascript interpreter executes a line var list = document.getElementsByClassName("first")[0]; there was no list element is defined, because body element is not yet executed.

So to get it worked, put a javascript code inside a function and call that function using the "onload" event on body tag. By doing this, the function will get called after loading of complete <body> element.

Upvotes: 3

August
August

Reputation: 1819

So the mistake was that script tag was entered before the body tag, after i moved to end of body it was fixed

Upvotes: 0

Related Questions