skip to Main Content

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


  1. For reference, this is to introduce jquery selector:

    https://api.jquery.com/category/selectors/

    For your problem, you could write the selector like:

    $(".mainPage > .pageWithButton > .btn").css("padding", "8px, 32px, 1px, 9px")
    

    In jquery, $(".a > .b") means to select elements which have class b and have a parent element with class a.

    Login or Signup to reply.
  2. You need to use the find() method.

    And, you’ll need to modify the if statement because $(".pageWithButton") is always true, regardless of there’s an element or not.

    $(".mainPage").each(function () {
        if ($(this).find(".pageWithButton").length > 0) {
            $(this).find(".btn").css("padding", "8px 32px 1px 9px");
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <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>
    
    <a href="" title="Learn more" class="btn btn-default" role="button" target="">Look up</a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search