Will the following code work?
var htmlattri="background-color:red;";
$('a').css("style",htmlattri);
If not, what is the correct solution?
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.
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.
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: $().
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With