Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add style to selector via jquery.?

Will the following code work?

var htmlattri="background-color:red;";
$('a').css("style",htmlattri);

If not, what is the correct solution?

like image 750
Cooldharma06 Avatar asked Apr 29 '13 05:04

Cooldharma06


People also ask

What is the use of the CSS () method in jQuery?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.

Can you use CSS selectors in jQuery for selecting elements?

Projects In JavaScript & JQueryjQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element.

Can we change CSS property using JavaScript and jQuery?

It is possible to change the CSS property of an element by using a simple JavaScript API, but we try to complete this challenge using jQuery css() method. Syntax: $().

How can use multiple CSS properties in jQuery?

Apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call. Here you can pass key as property and val as its value as described above.


1 Answers

You could add it to the style attribute:

$('a').attr('style', htmlattri);

But I would use .css():

$('a').css('background-color', 'red');

Or better yet, do it with a stylesheet and just use .addClass().

like image 119
Blender Avatar answered Sep 30 '22 18:09

Blender