Home > Enterprise >  how to change the background-Color on click of a button in javascript
how to change the background-Color on click of a button in javascript

Time:10-16

I was able to change the color of the text but i am not able to understand how to change the background color of the p tag. If someone can please let me know hoe to do it. Below is my HTML and JS code.

function button(){
var btn = document.getElementById('btn');
btn.addEventListener('click', function onClick(event) {
  // Change text color globally
  document.body.style.color = 'red';
});
}    
button();
<style>
        p{
            box-sizing: border-box;
            border: 1px solid black;
            height: 20px;
            width: 300px;
            text-align: center;
        }
    </style>
    
<p>Welcome To My Domain</p>



    <button id="btn">Button</button>

CodePudding user response:

You could add a class to the p tag and then query that within your event listener and set its style attribute, document.querySelector('.classname').style.backgroundColor = 'somecolor'

function button() {
  var btn = document.getElementById('btn');
  btn.addEventListener('click', function onClick(event) {
    // Change text color globally
    document.body.style.color = 'red';
    document.querySelector('.welcome').style.backgroundColor = 'black';
  });
}
button();
<style>
  p {
    box-sizing: border-box;
    border: 1px solid black;
    height: 20px;
    width: 300px;
    text-align: center;
  }
</style>

<p >Welcome To My Domain</p>



<button id="btn">Button</button>

Another way would be to toggle a class that styles your element for you. With this example add the class and style it in your css and then use the classList in javascript to toggle the class. document.querySelector('.className').classList.toggle('someclass')

function button() {
  var btn = document.getElementById('btn');
  btn.addEventListener('click', function onClick(event) {
    // Change text color globally
    document.querySelector('.welcome').classList.toggle('instance-change')
  });
}
button();
.instance-change {
  color: red;
  background-color: black;
}

p {
  box-sizing: border-box;
  border: 1px solid black;
  height: 20px;
  width: 300px;
  text-align: center;
}
<p >Welcome To My Domain</p>

<button id="btn">Button</button>

  • Related