Index.html
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<!-- jquery-3.4.1.min -->
<script type="text/javascript" src="custom.js"></script>
</head>
<body>
<div class="epic" style="color:red">hello this is title</div>
<div>hello this is title</div>
<input type="button" placeholder="click it" value="click">
</body>
</html>
custom.js
$( document ).ready(function($){
$(":button").click(function(){
$(".epic").attr("style","font-size:100px");
});
});
Now What I want Is when I click the button than I should be able to give the font-size that I want but keep the previous color red also . The code that I have written makes the font 100 but color is gone ,so Is there any way to keep the color and still be able to modify the font.
You can use .css()
to set the particular style property ( font-size ):
$( document ).ready(function(){ $(":button").click(function(){ $(".epic").css("font-size", "100px"); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="epic" style="color:red">hello this is title</div> <div>hello this is title</div> <input type="button" placeholder="click it" value="click">
Use .css
method instead. And pass a object of CSS properties. When you will call it again, it will just add the new properties to existing one.
In your solution, you are overwriting the complete style
attribute everytime. So it is removing the older properties.
$(document).ready(function() { $(":button").click(function() { $(".epic").css({ "font-size": "50px", "background-color": "blue" }); $(".epic").css({ "color":"white" }); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="epic" style="color:red">title</div> <div>hello this is title</div> <input type="button" placeholder="click it" value="click">
You could use the jQuery addClass()
method to keep the original CSS class and add a new one:
$("button").click(function(){
$(".epic").addClass("clicked");
});
And in the CSS:
.clicked {
font-size: 50px;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.