Reputation: 455
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.
Upvotes: 3
Views: 15517
Reputation: 2333
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>
Upvotes: 1
Reputation: 67505
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>
Upvotes: 2
Reputation: 8183
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>
Upvotes: 1
Reputation: 14669
specify id/class to element for better result.
$("input[type=button]").click(function () {
$("p").css("color", "red");
});
Upvotes: 0
Reputation: 3675
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>
Upvotes: 2