首先,很抱歉,如果这是一个简单的问题。我是 jQuery 的新手,我想知道如何检查元素是否存在,如果存在,则更改 css 属性。
这就是我的意思:我有以下列表:
<ul class="element-rendered">
<li class="element-choice">Item A</li>
<li class="select-inline">Item B</li>
</ul>
我想知道如何检查类 select-inline
是否存在于 element-rendered
中,如果存在,我该如何更改 的 css 背景code>element-choice
到蓝色?
我创建了一个 fiddle 重现此示例。
再次抱歉,如果这是一个简单的问题,但我是 jQuery 的新手。
最佳答案
您可以使用 .length
来检查元素是否存在于 DOM 中。
$('.element-rendered .select-inline')
将在类 element- 的元素内选择所有类
。选择器上的 select-inline
的元素呈现.length
将返回匹配元素的数量。所以,数字大于一,意味着元素存在。然后你可以使用.css
设置内联样式。
if ($('.element-rendered .select-inline').length) {
$('.element-choice').css('background', 'blue');
}
.element-choice {
width: 100%;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<ul class="element-rendered">
<li class="element-choice">Item A</li>
<li class="select-inline">Item B</li>
</ul>
我还建议您在 CSS 中使用类,并使用 addClass
将其添加到元素中。
关于javascript - jQuery:如何检查元素是否存在并更改 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32995297/