javascript - 如果 div 具有特定的 Child,则更改背景颜色

标签 javascript jquery html css if-statement

如果 div 有一个特定的子项,我正在尝试更改它的背景(和其他样式)。我正在使用 .length 来检查特定子项是否存在,但即使它不存在,div 也会从 jquery if 语句中获取样式。我的 HTML:

<div class="full-text-panel">
        <div class="main-wrap">
            <h1 class="home-h1">This is a header</h1>
            <a class="body-button">This is a button</a>
        </div><!--end main-wrap-->
    </div><!--end full-text-panel-->

还有我的 jQuery:

            var fullText = $('.full-text-panel');
            var bodyButton = $('.body-button');

            if ( $(".full-text-panel .body-button").length > 0 ) {
                fullText.css("background", "red");
            } else {
                fullText.css("background", "blue");
            }

我认为这行得通,但是两个全文本面板都采用了背景红色样式。我做错了什么?

最佳答案

$(function(){
  
  $('.full-text-panel:has(.body-button)').addClass('red');
  
  });
.full-text-panel{
  background:blue;
  }

.red{
  background:red;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="full-text-panel">
        <div class="main-wrap">
            <h1 class="home-h1">This is a header</h1>
            <a class="body-button">This is a button</a>
        </div><!--end main-wrap-->
    </div><!--end full-text-panel-->

<div class="full-text-panel">
        <div class="main-wrap">
            <h1 class="home-h1">This is a header</h1>
        </div><!--end main-wrap-->
    </div><!--end full-text-panel-->

关于javascript - 如果 div 具有特定的 Child,则更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29349689/

相关文章:

javascript - 在 onclick 事件中设置 css 属性

javascript - 登录并重定向到主页时无法获取 id

javascript - 虚拟键盘事件

php - 使用 jQuery mCustomScrollbars 调整 Div 高度大小在第一次加载时不正确

javascript - Node : Find mailto: section with cheerio

html - 清除两者都是摆脱居中

css - 消除 HTML5 Canvas 元素下方的重影边距?

javascript - 使用 PDF.js 将 PDF 静态转换为 HTML

python - 向 Folium map 添加标题或文本

javascript - 如果某些 dom 节点 float : left or they go down to a new line?,我如何用 javascript 判断