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

Leveraging functions in a Node.js module

I am struggling with using a function inside a Node.js module. I have implemented a custom sorting function to sort an array of objects based on the value of a specific property. exports.getResult = function(cards) { cards.sort(sortByField('suit& ...

Consistent sizing for Bootstrap thumbnail images

In my current project, I am implementing a Bootstrap thumbnail feature where each thumbnail consists of an image and a heading. However, a problem arose as the images do not have the same size, resulting in thumbnails with varying dimensions. To resolve th ...

The error of "Uncaught ReferenceError" is being triggered by the use of `process?.env?

A bug was discovered in our front-end code related to the following snippet: <span style={{ color: 'red' }}>{process?.env?.REACT_APP_HEADER_SUFFIX ?? ''}</span> The bug triggered the following error message: Uncaught Refere ...

What could be causing the ajax request to hang, yet miraculously go through when an alert is added?

I've been encountering a peculiar issue with my form submission. It seems that whenever I add a comment to the last alert section, the AJAX function fails to execute. However, if I remove the comment, it runs successfully. What could be causing this b ...

Having trouble extracting a JSON object from a POST request in Express v4 with the help of body-parser?

Currently, I am delving into the world of server-side code and learning about Node.js and Express. However, I am facing some challenges when it comes to receiving and parsing a JSON object sent from a POST request. Despite checking various resources (linke ...

How do I get my navbar to change color using a JavaScript scroll function?

I've been struggling with changing the color of my navbar when it's scrolled. I have some JavaScript code at the bottom that should handle this, but for some reason, it's not working as expected. I've double-checked that my bootstrap CD ...

How can I implement a for loop in Node.js?

I am currently experiencing an issue with my for loop while attempting to retrieve data from MongoDB and display it in the browser. The problem is that it only iterates through once, resulting in only the first entry being output. Strangely enough, when ...

Security Error when using the JavaScript map function in FireFox

My current dilemma involves using a JavaScript code to extract the above-the-fold CSS from my websites. Surprisingly, it functions flawlessly on Google Chrome. However, when I attempt to execute it on Firefox, an infamous 'SecurityError' occurs: ...

Unable to execute redirect function in Next.js 14 application

I've been working on implementing basic authentication within a Next.js app, however I'm encountering issues with redirecting to the homepage from the auth.ts file. Below is a snippet of the code where I am implementing the loginForm: //loginForm ...

The CSS selector functions as expected when used in a web browser, however, it

While conducting test automation using Selenium, I typically rely on css selectors to find elements. However, I recently came across a peculiar issue. I observed that in certain cases, the css selector works perfectly when tested in the browser console. Fo ...

What methods can be used to monitor changes made to thumbnails on the YouTube platform?

I have embarked on a project to create a Chrome extension that alters the information displayed on the thumbnails of YouTube's recommended videos. In this case, I am looking to replace the video length with the name of the channel. Imagine you are on ...

I'm looking for a way to add an onclick event to every element created by Vue.js through a "v-for" loop in order to toggle the visibility of its inner content

My Vue data consists of: data: function() { return { results: { "items": [ { "id": "770c257b-7ded-437c-99b5-3b8953b5be3a", "name": "Gsbssbb", "price": 9559, "colour": { ...

"When a Vuex mutation modifies the state, the computed property fails to accurately represent the changes in the markup

I've encountered a perplexing issue with using a computed property for a textarea value that hasn't been addressed in a while. My setup involves a textarea where user input is updated in Vuex: <textarea ref="inputText" :value="getInputText" ...

Unable to locate a resolution for the error message "Warning: Task "uglify" not found"

Below is the content of my Gruntfile.js: module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ uglify: { start: { files: { 'js/script.min.js': ['js/script.js&a ...

A guide on extracting data from a mongoose model and assigning it to a variable in a manner similar to the MVC design pattern

Below is an example of MVC framework code in PHP. I'm seeking advice on how to implement a similar process in Node.js using Mongoose. I am working with Node.js, MongoDB, and REST API development. Controller file: <?php class Myclass { public fu ...

Retrieve the current URL upon page load

I'm currently attempting to parse the URL in document.ready() so I can retrieve the id of the current page and dynamically populate it with content from an AJAX call. However, I've encountered an issue where 'document.URL' seems to refe ...

Can someone explain the meaning of this code?

Recently, I came across a project where this line of code was used in a jQuery script. I'm not sure of its purpose and would appreciate some help understanding why it was included. If necessary, I can provide the entire function for reference. $("#ta ...

The current layout of the div is hindering the ability to switch from vertical scrolling to horizontal scrolling

I'm currently utilizing this scroll converter tool to transform vertical scrolling into horizontal scrolling. However, despite correct script inclusion and initialization, the conversion is not working as expected. It seems like there might be an issu ...

Fancybox operates successfully when I manually include a class, yet fails to function when utilizing jQuery's .addClass() method

Below is a snippet of JS code that I use to add Fancybox classes to all hrefs on a webpage: $(function(){ //declaring target variable var $targetTable = $('.photo-frame a'); //looping through each table and adding the fancybox cla ...

I'm looking for a method in JavaScript that can search through my XML file to locate specific attributes and return the entire parent element containing that attribute. Can anyone help with

I'm completely new to XML and Javascript. I currently have this code in my HTML file: <select id="eigenschaften" name="eigenschaften" type="text" onchange=""> <option value="">Choose Property</option> <option value="soci ...