why can't i change innerHTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>document</title>
<style>
</style>
</head>
<body>
<div class="sa"></div>
<script>
var a = document.getElementsByClassName("sa").innerHTML;
a = "hi";
console.log(a);
</script>
</body>
</html>
output : output
i can't even see the code snippets: code snippets-1, code snippets-2
where is wrong in this code?,I searched but couldn't find the result I wanted, I'm not even sure I'm asking the right question, it happens every time I see an example but not when I do,i scare of stop myself in the start.
I'm trying to write hi to the div and check the hi in the console as a result I can't see what I'm typing on the page but I see it in the console
In your example, you get the innerHTML DATA, it is not a reference to the element's HTML. The a
variable is now a string of text. Therefore, when you try and change it, you change the value of a and NOT the innerHTML of the element.
Instead, get the element reference as below. Then set the innerHTML on that element.
Also, as you getting multiple elementS (plural), you will either need to loop after all, or get the first one. Often it's easier to just use document.querySelector('.sa')
when working with css selectors.
var a = document.getElementsByClassName("sa").innerHTML; // a is a string
a = "new";
console.log(a);
// You want
var aElement = document.getElementsByClassName("sa")[0]
aElement.innerHTML = "new";
<div class="sa">old</div>