html 如何使用JavaScript将CSS添加到特定的div类中,即使有多个div类具有相同的名称?

mnowg1ta  于 11个月前  发布在  Java
关注(0)|答案(2)|浏览(75)

我试图添加CSS样式到一个特定的按钮类。下面是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>

字符串
下面是JS:

<script>
    $('.mainPage').each(function(){
        if($(".pageWithButton")){
            $(".btn").css("padding", "8px, 32px, 1px, 9px")
        }
    })
</script>


我注意到的问题是,这段JS代码还将CSS样式应用于页面上具有btn类名的其他div类。如何限制CSS仅在mainPagepageWithButtonbtn中应用?

gj3fmq9x

gj3fmq9x1#

作为参考,下面是jquery selector的介绍:
https://api.jquery.com/category/selectors/
对于你的问题,你可以这样写选择器:

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

字符串
在jquery中,$(".a > .b")意味着选择类为b的元素,并且父元素的类为a

xggvc2p6

xggvc2p62#

您需要使用find()方法。
而且,您需要修改if statement,因为$(".pageWithButton")始终是true,无论是否存在元素。

$(".mainPage").each(function () {
    if ($(this).find(".pageWithButton").length > 0) {
        $(this).find(".btn").css("padding", "8px 32px 1px 9px");
    }
});

个字符

相关问题