Issues with JQuery .attr method not functioning as expected

I'm having trouble with the .attr() function in jQuery. It doesn't seem to be changing the background-color of the div with the id "outline" like I expected.

Here's an example of my code:

<div id="outline"></div>

And here is the CSS styling for the div:

#outline {
height: 300px;
width: 300px;
background-color: black;
}

This is the JavaScript (jQuery) code I wrote to change the background color to blue:

$("#outline").attr('background-color', 'blue');

Answer №1

background-color is not an HTML attribute, it is a style attribute - it should be used with the css function instead.

$("#container").css('background-color', 'red');
#container {
  height: 200px;
  width: 200px;
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="container"></div>

Answer №2

// You can use .css() to set the html style attribute
// .css() allows setting one or more styles at a time
$("#outline").css('background-color','blue');

// This code does the same thing as above
// .attr() is for setting one or more html attributes
$("#outline").attr('style', 'background-color:blue');
#outline {
height: 300px;
width: 300px;
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outline"></div>

Answer №3

Background color is not a regular attribute, but a CSS property.

For changing the background color, use the following code:

$("#outline").css('backgroundColor', 'blue');

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

Show the response obtained after making a POST request

In my current project, I am utilizing vanilla JavaScript to send a POST request to my Flask App. I have implemented a validation feature that checks for duplicate usernames when a user is signing up. If the username already exists, a 406 status response is ...

Retrieve the genuine HTML code for a control directly on the client side

My goal is to retrieve the complete HTML text for a control from the client browser. This is important because certain information, especially the "Style," does not appear on the server side. How can I obtain the entire HTML text for a control? ...

Broadcast and listen to events in AngularJS using `$rootScope.$emit`

I am currently working on a large Angular app and I have encountered the need to trigger an event using $rootscope.$emit, and then listen to this event inside a factory. Doing this inside a controller is not feasible because the controller hasn't load ...

Guide on accessing the fastify application instance within an imported module

Currently, I am working on developing a rest API using Fastify and I am in the process of organizing my code into separate files for better structure. One issue I am facing is how to access the Fastify instance within a file that I import. The following s ...

What steps can I take to ensure that WebStorm properly recognizes a package's functions?

No matter what I do, WebStorm refuses to stop throwing inspection warnings when I try to use the JOI package in my node.js project. The code runs fine and there are no runtime errors, but the warning persists. I have updated the package, explicitly install ...

Is there a way to dynamically enable ui-sref through element.append in Angular?

I am in the process of developing a pagination directive. Once the total_for_pagination data is filled, the appropriate HTML for the pagination gets generated. Here's my current HTML structure with a maximum of 50 per page: <pagination data-numbe ...

Uploading multiple files simultaneously in React

I am facing an issue with my React app where I am trying to upload multiple images using the provided code. The problem arises when console.log(e) displays a Progress Event object with all its values, but my state remains at default values of null, 0, and ...

Add a Time Stamp to the Ajax URL Query

I'm attempting to add a timestamp to my URL that is being called by AJAX every 5 seconds. The purpose is to prevent caching in Internet Explorer browsers. However, it seems like the AJAX call is not functioning properly now without any error messages. ...

Error in accessing a null property in JavaScript on a different HTML page

My website consists of multiple HTML pages that are all linked to the same JavaScript file containing several IIFE functions. One of the functions is responsible for controlling a specific button that only appears on one page. However, when accessing other ...

JavaScript Bug Report

Currently, I am immersed in a project that encompasses various languages like HTML, JS, and PHP. While working on one of the PHP functions, I stumbled upon an unexpected anomaly. To dissect it better, I decided to break it down into simpler functions: &l ...

Displaying incorrect symbols with icon fonts

I have successfully integrated icon fonts into my simple web page. Check it out on jsFiddle here My design is similar to this example, but instead of bars, I see a snake icon displayed. How can I fix this issue with the fonts? Here is the code snippet: ...

Troubleshooting Problem with jQuery Submit on Chrome in ASP.NET MVC 3 Ajax.BeginForm

Hey everyone, I've been trying to solve a problem all morning without any luck. Here's the issue -> I have an Ajax.BeginForm that is triggered by a checkbox using jQuery: <% using (Ajax.BeginForm("Edit", "Products", ...

Populate the div with the URL parameter only when another span element is empty after a specified time interval using setTimeout

When displaying a person's name on a page, there are two different methods to consider. It can be extracted from the URL or retrieved from an email form in the CMS used. However, these two approaches sometimes conflict with each other. Currently, I h ...

Does CSS Horizontal Padding Percentage Stop Relative to Element Once Maximum Width is Reached?

I'm currently in the process of developing my latest portfolio website at and I'm facing a perplexing padding dilemma that has left me stumped. The approach I'm taking with the layout involves each row of content consisting of both an outer ...

Executing a protractor test on Safari results in the message "Angular was not located on the webpage https://angularjs.org/"

Recently, I encountered an issue while trying to run a Protractor test on Safari, even when following the official example provided at http://www.protractortest.org/. Below are my conf.js and todo-spec.js files. The problem arises when I set browser.ignor ...

Determine if an option is chosen in multiple select elements using Vanilla JavaScript

In order to determine if a checkbox is checked, we use the following code: let isChecked = event.target.checked But what about multiple select options like the example below? <select name="books[]" multiple> <option value="A">A</option& ...

The Input Boxes Are Too Broad

Currently, I am working on a responsive web page that features a form. However, I have noticed that all the input elements are spilling out of the form both from the left and right sides. Can someone please shed some light on why this could be happening? ...

Having trouble sending a GET request from the client to my backend route using axios in a React-Node.js/Express setup. Where did I go wrong?

Struggling with making an API request from my backend route (using nodes/express). I'm making an axios request from the client site using React. The express backend route works fine, so the issue must be in my client-side code. I've been stuck on ...

Display the element solely when the user enters a value greater than 0 into the input box

I am in the process of developing a WoW Classic statistics calculator that allows users to select a class and input various values. As the user makes changes to the inputs, the calculations are displayed below the form using vanilla JS and jQuery. I am ple ...

What is the best way to zoom in on an image and make it move off the screen as I scroll through my webpage?

I am working on a website design where I would like to implement an image zoom effect as the user scrolls down. Additionally, I want the image to move to either the left or right side of the screen as it goes out of view when scrolling to the bottom. While ...