Reputation: 1
Hi i’m having trouble changing the class of a CSS with javascript, whenever I call the element and try to change the style it returns null, almost like the element doesn’t have the class associated my code looks like this
var box = document.getElementById('box1');
box.style.backgroundColor = red;
.box {
background-color: black;
}
<div id=“box1“ class="box">
Somehow when you log in the console the style of box (of the js) the background color is empty
Upvotes: 0
Views: 616
Reputation: 4453
setTimeout(function() {
$(".box").css("background-color", "red");
}, 3000);
.box {
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id=“box1” class="box">Box 1</div>
Upvotes: 0
Reputation: 7979
You can change CSS using .css() of jquery.
Try:
$( document ).ready(function() {
$('#box1').css("background-color", "red")
})
.box {
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="box1" class="box">
CSS
</div>
Upvotes: 0
Reputation: 897
this should work
var box = document.getElementById('box1');
box.style.backgroundColor = "red"; //you were just typing red earlier
box.style.width="100px";
box.style.height="100px";
Upvotes: 0
Reputation: 6752
Use correct quotations around your ID attribute. Also use "red" instead of just red.
var box = document.getElementById('box1');
box.style.backgroundColor = "red";
.box {
background-color: black;
}
<div id="box1" class="box">
CSS
</div>
Upvotes: 1