A step-by-step guide to updating the background color in JavaScript when a button is clicked

I successfully changed the text color, however, I am struggling to figure out how to change the background color of the p tag. If anyone could provide guidance on how to accomplish this, it would be greatly appreciated. Below you will find my HTML and JS code snippets.

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;
            background-color: lightblue; /* Added background color style */
        }
    </style>
    
<p>Welcome To My Domain</p>



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

Answer №1

You have the option to assign a class to the p tag and then refer to it in your event listener to modify its style using:

document.querySelector('.classname').style.backgroundColor = 'somecolor'

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

<p class="welcome">Welcome To My Domain</p>



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

Another approach is to toggle a class that applies styling to your element. In this example, define the class with styles in your CSS file and then use classList in JavaScript to toggle the class.

document.querySelector('.className').classList.toggle('someclass')

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

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The method window.scrollTo() may encounter issues when used with overflow and a height set to 100vh

Suppose I have an HTML structure like this and I need to create a button for scrolling using scrollTo. However, I've come across the information that scrollTo doesn't work well with height: 100vh and overflow: auto. What would be the best way to ...

Instructions for accessing a website with JavaScript authentication

Attempting to log in to a website using Java script. Found the login form on the site but unsure of next steps. Added values "myemail" and "mypass" while inspecting code, successfully logged in. Having trouble incorporating Java script function into own c ...

The divs descend one after another with no problems related to margins or padding

Having some trouble creating a unique WordPress theme with Bootstrap3. I can't seem to get my divs to behave properly and I've tried everything from display: inline, vertical-align: top, floats, clears, etc... but nothing seems to work. Here is ...

The variablewidth feature in Slick Carousel is malfunctioning

I've integrated slick slider 1.8.1 into my Rails app (v.5.2.0) and I'm encountering an issue with variablewidth set to true. My expectation was to achieve a layout similar to the example shown here: https://i.sstatic.net/5QFRx.jpg However, what ...

Incorporating dynamic variables into Shopify's settings.html page

Are there ways to integrate templating into Shopify's settings.html? I attempted adding the extension settings.liquid, enabling Liquid templating within the settings document, but it was unsuccessful. In my settings.html file, I include various field ...

Require assistance with an unoccupied Django dialog box

Looking to implement a popup in a django template, but encountering an issue where the popup appears empty. Below is the current code: <input type="button" value="{{ account.account_id }}" class="btn btn-primary" data-toggle="modal" data-target="#myMo ...

"Enhance your images with dynamic captions using jQuery

Struggling to create an image caption that only appears when hovering over the specific image? Not sure how to select the correct object? The caption is working, but it's appearing for all images at once. I have attempted to target a single image wit ...

Attach the footer to the bottom of the screen only if the main page text is limited in length

How can I ensure that my footer sticks to the bottom of the screen only when there is minimal content on the page? When there is a lot of content, I'd like the footer to appear after the content rather than being pinned at the bottom, especially since ...

Eliminate php file extensions using .htaccess

Currently, I am developing a script and looking to change the links in the following way: www.mysite.com/sign-up.php to www.mysite.com/sign-up and www.mysite.com/profile.php?username=abc to www.mysite.com/profile/abc I have come across this code that ...

Eliminating Unnecessary Stylesheets in Vite and Vue Website

When working on the Vite-Vue application, I noticed that the styles I implemented for both index.html and Vue components/views are showing up as crossed out in the browser. Additionally, many of the styles I added to the components/views are also being cro ...

Checking if the group of radio buttons has been selected using JQUERY

Need help with validating a group of radio buttons. If none are checked, display an error message in the span element to prompt users to select an option. The strange issue I am facing is that the validation code works only when placed below the radio butt ...

Struggling to line up three images with linked attachments in a single row using Bootstrap 4

Currently tackling my portfolio for a school project, I find myself stuck on organizing my projects in a single line. Here is the code snippet that's giving me trouble... <div class="container"> <div class="row"> <div class= ...

Looking for a skilled JavaScript expert to help create a script that will automatically redirect the page if the anchor is changed. Any t

Seeking a Javascript expert, In my custom templates, I have used a link as shown below: <a href='http://www.allbloggertricks.com'>Blogging Tips</a> I would like the page to redirect to example.com if the anchor text is changed from ...

Set the background of the vue widget to be completely see-through

I have a project where I am creating a widget using Vuetify, and embedding it into another website in the following way: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="component-styl ...

Leveraging src css within the React public directory

I have set up my React application to import a stylesheet from the src folder using import './css/styles.css' at the top of App.js. In the public folder, I have created a basic /docs/index.html file that is linked to from the React app but opera ...

Tips for JavaScript validation before submitting a form in Zend framework

I created this JavaScript code for form validation, but it is also submitting data to the database even when the validation fails. I need help in modifying the code so that it only submits the data if the conditions are met. Below is the HTML code: <f ...

Manipulating Object origin data

I'm unsure if this can be achieved. I am aiming to create a header and footer that remain the same while only switching the content pages. The resources I have at my disposal cover HTML, JS, CSS, and JQuery. Below is a simplified version of my curre ...

Making <div> elements responsive by rearranging their display order using CSS in media queries, troubleshooting issues with floats, and adjusting font sizes

I'm currently working on a webpage located at: On this page, there is a containing division with 5 elements inside. They are floated left in order to align vertically, but I am facing some challenges when it comes to adjusting my CSS for media querie ...

Struggling to make updates to News.php (Page Template) in WordPress, yet seeing no changes reflected in the browser

For some reason, the footer on my news page is located inside of the container. It's odd because the actual file has the footer code positioned outside of the container. I can't seem to figure out what is causing the footer to move unexpectedly. ...

Using jQuery to animate a div element with CSS3

After creating a loader using CSS3 and CSS3 Animations, I am looking to implement the actual loading function with jQuery based on a specified duration. For instance, setting it to load fully in 30 seconds. This is what I currently have: < ...