Reputation: 25
I want to change the text color of an element when I click a button using jQuery. This code is not working, please help!
$(document).ready(function() {
$("p").click(function() {
$(this).hide();
});
$("button").click(function() {
$("#colorChange").style.color = "blue";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="colorChange">I should(?) change color when you click mr. button</p>
<button>clickme</button>
Upvotes: 0
Views: 62
Reputation: 1
Please try this,
$("button").click(function(){
$("#colorChange").css("color","blue");
});
this one also works fine,
$("button").click(function(){
$("#colorChange")[0].style.color= 'blue';
});
Upvotes: 0
Reputation: 1766
The problem is this line:
$("#colorChange").style.color = "blue";
It should look like this:
$("#colorChange")[0].style.color = "blue";
This is because the object returned from $("#colorChange")
is a jQuery Object. The style property you wish to change is a member of a DOM Element, which can be retrieved from the jQuery Object with an array index or the get()
method.
Upvotes: 0
Reputation: 151
Try using $("#colorChange").css("color", "blue")
instead of $("#colorChange").style.color = "blue"
.
For more info, visit: https://api.jquery.com/css
Upvotes: 0
Reputation: 76
hope this help
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
$("button").click(function(){
$("#colorChange").css("color","blue");
});
});
</script>
</head>
<body>
<p id="colorChange">I should(?) change color when you click mr. button</p>
<button>clickme</button>
</body>
</html>
Upvotes: 1