0

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>

2
  • api.jquery.com/css Use the correct functions. jQuery does not directly expose attributes/properties of dom elements. Commented Nov 20, 2018 at 17:49
  • Alternatively you could get the raw dom element with $("#colorChange")[0] and your property access would work fine. Commented Nov 20, 2018 at 17:57

4 Answers 4

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Explain what the issue is and how you fixed it. Don't just post code.
@AboAlimk thank you, as you can tell im new to jQuery and didnt realize you cant use plain javascript methods with jQuery selectors
0

Try using $("#colorChange").css("color", "blue") instead of $("#colorChange").style.color = "blue".

For more info, visit: https://api.jquery.com/css

Comments

0

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.

Comments

0

Please try this,

$("button").click(function(){
     $("#colorChange").css("color","blue"); 
});

this one also works fine,

$("button").click(function(){
     $("#colorChange")[0].style.color= 'blue'; 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.