i am new in jquery i want to know that i am trying to apply style using attr() i have given four style but it is applying last one style i want to know that does it always apply last one style or not?
<!DOCTYPE html>
<html>
<body>
<p id="prg1">first paragraph</p>
</body>
<script src="C:\Users\SUDARSHAN\Desktop\html_UI\jquery-3.6.0.js">
</script>
<script>
$('document').ready(function (){
$('#prg1').attr({style:'color:yellow',style:'font-family:arial',style:'color:yellow',style:'border-style:dotted'});
})
</script>
</html>
CodePudding user response:
The style
attribute is a single string containing many styles like this
<div style="color:yellow; font-family:arial; border-style:dotted">
So every time you apply it you're replacing the last string. So you'd have to do the following with one big string.
$('#prg1').attr('color:yellow; font-family:arial; border-style:dotted')
However, this really isn't the best use case for attr()
.
Instead, use the JQuery .css()
method which can set (and get) styles.
$('#prg1')
.css('color', 'yellow')
.css('font-family', 'arial')
.css('border-style', 'dotted')
or you can use an object in a single call
$('#prg1').css({
'color': 'yellow'
'font-family': 'arial',
'border-style': 'dotted'
})
CodePudding user response:
You could use .addClass()
jquery
$('document').ready(function (){
$("#prg1").addClass("important");
});
css
<style>
.important {
color:yellow;font-family:arial; color:yellow; border-style:dotted;
}
</style>