Why doesn't document.getElementsByClassName functiton work for me

Here is my code and I am not able to see the x variable in the webpage. it worked if i used the
document.getElementsById() function. I also gave the class name to the p tag as demo but still it did not work.
Js file:
var x=6 ;
var y=3;
var m = x*y

document.getElementsByClassName(“demo”).innerHTML = m ;
Html file:



	<title>Java Webpage </title>

	<h1> Java script</h1>
	<p class="demo" style="color: red"></p>
		<script type="text/javascript" src = "my-java-script.js"></script>


The problem is documet.getElementsByClassName returns a node list , unlike getElementById hence “Elements”.
So you’ve to make a slight adjustment to you JS code as follows:

var z=document.getElementsByClassName(“demo”);

In the above code var z will store all the elements which have class name as “demo” . and z[0] will point to the first element which in our case is the only element

. Also make sure all your JS statement ends with a semicolon( ; ) (the statement var m=x*y was missing one).
and to check for JS related error you can use console window of the inspector tab of any web browser. All the JS related error will be logged there. Hope this helps :slight_smile: .

1 Like

@akhil , thanks so much bro.

Glad i could help :slight_smile: .

1 Like