- How to set the background color for an element using jQuery?
- Approaches to set background color for an element in jQuery
- Using CSS() method
- Syntax
- Example
- Setting background color using jQuery - css() method
- Output
- Using attr() method
- Syntax
- Example
- Output
- Using addClass() method
- Syntax
- Example
- Output
- Conclusion
- Получение и установка CSS-свойств элементам в jQuery
- Как получить стиль элемента в jQuery
- Как изменить или добавить стиль к элементу в jQuery
- Как удалить определённый стиль у элемента
- jQuery — css() Method
- Return a CSS Property
- Example
- Set a CSS Property
- Example
- Set Multiple CSS Properties
- Example
- jQuery Exercises
- jQuery CSS Reference
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
How to set the background color for an element using jQuery?
jQuery- a very popular JavaScript tool that helps in simplifying the process of web development consists of various tools that can be used to manipulate the HTML elements, CSS properties, and even event handling. Adding new or modifying styles of an HTML element dynamically is one such task that requires based on user interaction.
jQuery has various methods by which we can set the background color of an HTML element in using jQuery. We will see some different approaches including, using the CSS () method, using the addClass() method, and using the attr() method. Every method has its pros and cons, and choosing the right one depends on the specific needs of the application.
In this article, we will see how to set the background color for an element in HTML using jQuery.
Approaches to set background color for an element in jQuery
Setting the background color for an HTML is a very simple task but being simple, there are multiple ways through which the same task can be done. Let’s now see some of the different ways through which we can do this −
Using CSS() method
The first method is the CSS() method which is used to set the CSS properties to an HTML element. We can use this method also to set the background color of an element. To do that we can pass the CSS property name and value as arguments.
Syntax
See the following syntax for more detail −
Here, we are selecting the span element and set its background color to green at the click of the button.
Example
See the below example to understand how we can set the background color for an element using the css method.
/* This is our default style for span element*/ #bgSpanSetting background color using jQuery - css() method
Welcome to Tutorialspoint
Output
In the above example, we have created a button that when clicked, sets the background color of the span element having id as “bgSpan” to lightgreen color with the help of the CSS () method.
Using attr() method
The attr() method is used to set the attributes of an HTML element. Now, this method can also be used to set the style attribute of an element for defining the CSS properties. To set the background color of an element with this method, we can pass the style attribute with our CSS properties as an argument.
Syntax
See the following syntax for more detail −
Here, we are selecting the span element and setting its background color to green and the border of 1px solid green also at the click of the button.
Example
See the below example to understand how we can set the background color for an element using the attr() method.
/* This is our default style for span element*/ #bgSpan Welcome to Tutorialspoint
Output
In the above example, we have created a button that when clicked, sets the style attribute of the span element having id as “bgSpan” to «background-color: lightgreen» using the attr() method. As compared to the above approach, this method is more powerful and simultaneously having error-prone because we need to use the correct syntax for the CSS rule.
Using addClass() method
Another way to set the background is by using the addClass() method. This method is used to add one or more classes to selected elements. To do this, we have to define some CSS rules for these classes in our stylesheet. But to set the background color for an element, we have to define a class with the desired background color and add it to the element.
Syntax
See the following syntax for more detail −
Here, we have defined a CSS class with the name «green-background» in the stylesheet having a background color of green. Now, when the button is clicked, this class is added to the span element.
Example
See the below example to understand how we can set the background color for an element using the addClass() method.
/* This is our default style for span element*/ .green-background Welcome to Tutorialspoint
Output
In the above example, we have created a button that when clicked, sets the style attribute of the span element having a class with the name “green-background” to «background-color: green» using the addClass() method. It also sets the four different CSS properties at the click of a button including setting the height, width, padding, and font-size.
Conclusion
In this article, we have learned multiple methods of how to set the background color of an element using a powerful library called jQuery. We have seen the different methods to set the background color which include the CSS() method, the attr() method, and the addClass() method. All of these methods are some of the commonly used methods to style HTML elements using jQuery. First, we saw the CSS() method that is used to set the CSS properties of an element then we saw another method called the attr() method which is used to set the attributes of an element and with the help of this, we can also set the background color of an element. The last method we saw was the addClass() method which adds a class to an element to define the CSS properties of an element. Choosing any method from the above all methods depends on the project requirements, etc. So, carefully select and use the method as per your requirement keeping in-mind their pros and cons.
Получение и установка CSS-свойств элементам в jQuery
В jQuery работа со стилями HTML элементов осуществляется через метод css . Данный метод используется как получения значения стилей, так и для их добавления, изменения и удаления.
Как получить стиль элемента в jQuery
Первый вариант метода css — это получение окончательного значения CSS-свойства непосредственно применяемого к элементу.
// Вариант 1 (получение окончательного одного CSS свойства) .css( propertyName ) // propertyName (тип: Строка) – имя CSS-свойства, значение которого нужно получить .css( propertyNames ) // propertyName (тип: Массив) – массив, состоящий из одного или нескольких CSS-свойств, значения которых нужно получить
Данный метод, если его применить к набору элементов, возвращает значение CSS свойства только для первого его элемента.
Пример, в котором получим цвет фона непосредственно применённого к элементу #header :
var bgHeader = $('#header').css('background-color');
В jQuery названия CSS-свойств можно указывать как в CSS, так и как это принято в JavaScript. Т.е. убирать дефисы и заменять буквы, следующие за каждым дефисом на прописные.
// можно и так var bgHeader = $('#header').css('backgroundColor');
Если необходимо получить значения указанного CSS свойства или набора этих свойств у всех элементов текущего набора, то в этом случае необходимо использовать, например, метод each.
Например, определим значение свойства display у всех выбранных элементов и выведем их в консоль:
// переберём все элементы .container $('.container').each(function(index){ // значение css-свойства display текущего элемента набора var display = $(this).css('display'); // выведем результат в консоль (индекс элемента в наборе и его значение css-свойства display) console.log(index + '. display = '+ display); });
Кроме этого, метод css позволяет также получить сразу несколько CSS свойств у элемента.
Например, при нажатии на HTML элемент div выведим его ширину и высоту:
.
Как изменить или добавить стиль к элементу в jQuery
Установить стиль элементу осуществляется тоже с помощью метода css, но в этом случае используется следующий синтаксис:
// 1 вариант (для установки одного стиля элементу) .css( propertyName, value ) // 2 вариант (установка значения стиля с помощью функции) css( propertyName, function ) // 3 вариант (для установки несколько стилей элементу) css( properties ) // Описание параметров: // propertyName (тип: String) – имя CSS-свойства // value (тип: String или Number) – значение, которое нужно установить CSS-свойству // function – функция, результат выполнения которой будет установлен в качестве значения CSS-свойству // Синтаксис функции: // Function( Integer index, String value ) => String или Number // В качестве аргументов функция получает индекс элемента (index) и текущее окончательное значение CSS-свойства (value) // properties (тип: объект JavaScript, содержащий ноль или более пар ключ-значение) – объект, состоящий из пар DOM-свойство-значение, которые нужно установить элементу.
При установлении стилей с помощью метода css , они задаются ко всем элементам текущего набора.
Например, добавим ко всем элементам .info серый цвет фона (background):
Если необходимо применить к каждому элементу текущего набора сразу несколько CSS свойств, то в качестве параметра этого метода необходимо использовать объект JavaScript, содержащий пары ‘имяСвойства’ : значение.
.css({'имяСвойства1':значение, 'имяСвойства2':значение. })
Пример, в котором показано как можно задать несколько CSS-свойств к элементам .success :
$('.success').css({ 'color':'green', 'font-size':'16px' });
В качестве значения строки также можно использовать относительные значения, которые начинаются с += или -= . Первое выражение используется для увеличения текущего значения CSS свойства, а второе — для уменьшения.
Например, увеличим отступ слева и справа у элементов .container на 10px :
$('.container').css({ "padding-left": "+=10", "padding-right":"+=10" });
Ещё один способ использования метода css — это применение в качестве 2 параметра функции.
.css('имяСвойства',функция) // функция: Function( Integer index, String value ) => String или Number
Вариант использования метода css, у которого в качестве второго параметра используется функция обычно находить применение, когда значение необходимо как-то вычислить или определить по какому-то алгоритму.
Например, установим всем элементам .text , у которых цвет шрифта не равен чёрному, CSS свойство color , равное red .
$('.text').css('color',function(index,value){ if (value!=='rgb(0, 0, 0)') { return 'red'; } });
Например, поменяем значение CSS свойства width у всех элементов img на странице, находящихся #content :
Как удалить определённый стиль у элемента
Для того чтобы в jQuery убрать определённый стиль у элемента, ему необходимо присвоить просто пустую строку.
Например, уберём у всех изображений на странице CSS свойство height :
jQuery — css() Method
The css() method sets or returns one or more style properties for the selected elements.
Return a CSS Property
To return the value of a specified CSS property, use the following syntax:
The following example will return the background-color value of the FIRST matched element:
Example
Set a CSS Property
To set a specified CSS property, use the following syntax:
The following example will set the background-color value for ALL matched elements:
Example
Set Multiple CSS Properties
To set multiple CSS properties, use the following syntax:
The following example will set a background-color and a font-size for ALL matched elements:
Example
jQuery Exercises
jQuery CSS Reference
For a complete overview of all jQuery CSS methods, please go to our jQuery HTML/CSS Reference.
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.