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 right solution?

+6
source share
7 answers

You can 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 style and just use .addClass() .

+22
source

Try the following:

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

or

 var style ="background-color:red;"; $("a").attr("style", style); 
+2
source
You were almost there. You must specify the parameter name and value separately: $('a').css("background-color","red");
+1
source

Use this

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

OR you can also use this type

 $('a').css({background-color:'red'}); 
+1
source

You can achieve this by doing the following:

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

But you should not do this directly on the hyperlink. You must create a class or Id and add this CSS class for a specific class or id.

HTML: -

  <a href="#" class="link" id="link">Test</a> 

JQuery: -

  $('#link').css("background-color",red); 
0
source

try the following code:

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

0
source
 $('a').css('backgroundColor': 'red'); 
0
source

Source: https://habr.com/ru/post/943853/


All Articles