3

I have a text like following :

<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
<button>COLORCHANGER<button>

I want to change the text color when I click the button.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Nuisance
  • 286
  • 1
  • 2
  • 15
  • What have you try to achieve color change? Show some code that you wrote to do this. – Daniel Krawieczyński Aug 05 '16 at 10:53
  • possible duplicate of[http://stackoverflow.com/questions/17925577/change-text-color-with-javascript](http://stackoverflow.com/questions/17925577/change-text-color-with-javascript). – Rishal Aug 05 '16 at 10:54

5 Answers5

2

First, you need to find the element that you want to change colors for by using document.getElementsByTagName("button")[0]; and store it in a variable.

Next, use an event listener on the button element to listen for a click.

When the click executes, the p element will change its color to blue.

var colorChanger = document.getElementsByTagName("button")[0];
colorChanger.addEventListener("click",function() {
  document.querySelector('p').style.color = "blue";  
});
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
 <button>COLORCHANGER<button>
Wowsk
  • 3,637
  • 2
  • 18
  • 29
2

Attach click event to the button using addEventListener('click') then change the color of your text using .style.color = 'color', check example below.

NOTE : It will be better if you give your elements an identifier.

Hope this helps.

document.querySelector('button').addEventListener('click', function(){
    document.querySelector('p').style.color='green';
})
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
<button>COLORCHANGER</button>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

document.getElementsByTagName("button")[0].addEventListener("click",function() {
  document.querySelector('p').style.color = "red";  
});
 <p id = 'textToChange'><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
 <button>COLORCHANGER<button>
Aleksandar Đokić
  • 2,118
  • 17
  • 35
1

function changeColor(){
var element = document.getElementById("questionContainer");
element.className = "myClass";
}
.myClass{
 color:red; 
 }
<div id="questionContainer"> 
<p><strong><em> QUESTION: WHAT IS YOUR NAME?</em></strong></p>
  </div>
 <button onclick="changeColor()">COLORCHANGER<button>
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
0

specify id/class to element for better result.

       $("input[type=button]").click(function () {
            $("p").css("color", "red");
        });