I am trying to add CSS style to a particular button class. Here is the HTML:
<div class="mainPage">
<div class="pageWithButton">
<div>
<a href="" title="Learn more" class="btn btn-default" role="button" target="">Look up
<i class="fas fa-search"></i>
</a>
</div>
</div>
</div>
Here is the JS:
<script>
$('.mainPage').each(function(){
if($(".pageWithButton")){
$(".btn").css("padding", "8px, 32px, 1px, 9px")
}
})
</script>
The problem I’m noticing is that, this JS code is also applying the CSS styles to the other div classes on the page that have a btn
class name . How can I limit the CSS to only be applied inside this mainPage
pageWithButton
with btn
?
2
Answers
For reference, this is to introduce jquery selector:
https://api.jquery.com/category/selectors/
For your problem, you could write the selector like:
In jquery,
$(".a > .b")
means to select elements which have classb
and have a parent element with classa
.You need to use the
find()
method.And, you’ll need to modify the if statement because
$(".pageWithButton")
is alwaystrue
, regardless of there’s an element or not.