I am trying to set some properties of a div element using javascript, but the properties are not being set, I used the inspect mode in the browser, and It says: Uncaught TypeError: Cannot read property 'style' of undefined
I already tried to use an ID attribute to get the element and even querySelector method but nothing changes
<body>
<div id="app">
<div class="box"></div>
</div>
<script>
var boxElement = document.getElementsByClassName('.box')[0];
boxElement.style.width = 100;
boxElement.style.height = 100;
boxElement.style.backgroundColor = '#f00';
</script>
</body>
I am trying to set some properties of a div element using javascript, but the properties are not being set, I used the inspect mode in the browser, and It says: Uncaught TypeError: Cannot read property 'style' of undefined
I already tried to use an ID attribute to get the element and even querySelector method but nothing changes
<body>
<div id="app">
<div class="box"></div>
</div>
<script>
var boxElement = document.getElementsByClassName('.box')[0];
boxElement.style.width = 100;
boxElement.style.height = 100;
boxElement.style.backgroundColor = '#f00';
</script>
</body>
Share
Improve this question
asked Aug 28, 2019 at 20:52
EduardoEduardo
4251 gold badge5 silver badges12 bronze badges
2
|
5 Answers
Reset to default 3The getElementByClassName implies that the selector's name is a class, so you don't need the dot in front of it. Same as you don't need the # with getElementById.
var boxElement = document.getElementsByClassName('box')[0];
EDIT: as others are already pointed it out, there is no need for the getElementByClassName()
function, you can just use the querySelector()
function in order to avoid an array as the result.
Incorrect syntax. Remove the .
in the getElementsByClassName('.box')
.
If you would like to use the class selector you could use document.querySelectorAll('.box')
use this (by Id name):
document.getElementById('box').setAttribute("style", "width:100px;height:100px;background-color:#f00;");
HTML:
<div id="app">
<div id="box"></div>
</div>
or use this (by class name) :
document.getElementsByClassName('box')[0].setAttribute("style", "width:100px;height:100px;background-color:#f00;");
HTML:
<div id="app">
<div class="box" ></div>
</div>
<script>
var boxElement = document.querySelector('.box')
boxElement.style.width = '100px'
boxElement.style.height = '100px'
boxElement.style.backgroundColor = '#f00'
</script>
This is my resolution for the problem, he needs use a 'px'after CSS code
in my case I added extra td in body like below
<td>200</td>
but forgot to add this in the head section
<th>Fees</th>
var boxElement = document.getElementsByClassName('box')
– sanketd617 Commented Aug 28, 2019 at 20:53document.querySelector('.box');
(no[0]
). – junvar Commented Aug 28, 2019 at 20:54