使用jQuery在DOM中查找元素

时间:2016-01-06 09:40:17

标签: jquery html

我使用jQuery来检查一个元素是否存在但我的代码不起作用...有人可以解释一下我做错了什么吗?

如果variable-list-wrapper的元素包含类empty-list-caption,则将color blue添加到表格中。

HTML:

   <div class="variable-list-wrapper">
        <table tabindex="0" class="variable-list table table-striped">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Value</th>
                </tr>
            </thead>
            <tbody>
              <tr class="not-sortable">
                <td colspan="1000">
                  <var class="empty-list-caption">No variables</var>
                </td></tr>
            </tbody>
        </table>
    </div>

jQuery的:

$(document).ready(function(){
    if($(".variable-list-wrapper").hasClass("empty-list-caption")) {
    $("table.variable-list").css("color","blue");
  }
});

4 个答案:

答案 0 :(得分:3)

hasClass用于确定所选元素是否已应用类,而不是查找子元素。

要执行您需要的操作,您可以使用find()并检查length属性以确定是否找到了任何内容,如下所示:

if ($(".variable-list-wrapper").find(".empty-list-caption").length) {
    $("table.variable-list").css("color", "blue");
}

或者您可以使用:has选择器来取消对if语句的需求:

$(".variable-list-wrapper:has(.empty-list-caption) table.variable-list").css("color", "blue");

请注意,最好在CSS文件中设置样式,然后使用jQuery向元素添加或删除类。

答案 1 :(得分:0)

尝试使用find(),如下所示:

$(document).ready(function(){
    if($(".variable-list-wrapper").find(".empty-list-caption").length == 1) {
    $("table.variable-list").css("color","blue");
  }
});

答案 2 :(得分:0)

我相信你应该更好地使用&#34; .length&#34;到您的父元素或子元素:

$(document).ready(function(){
    if($(".variable-list-wrapper").length){
      $("table.variable-list").css("color","blue");
    }
});

答案 3 :(得分:0)

试试此代码

$componentTemplateNodes