Reputation: 425
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>
Upvotes: 6
Views: 110038
Reputation: 2480
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>
Upvotes: 0
Reputation: 1
<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
Upvotes: 0
Reputation: 159
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>
Upvotes: 1
Reputation: 997
The 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.
Upvotes: 3
Reputation: 1474
Incorrect syntax. Remove the .
in the getElementsByClassName('.box')
.
If you would like to use the class selector you could use document.querySelectorAll('.box')
Upvotes: 3