jQuery:如何检查元素是否存在并更改css属性 [英] jQuery: How to check if an element exists and change css property
问题描述
首先,很抱歉,如果这是一个简单的问题.我是jQuery的新手,我想知道如何检查元素是否存在,如果存在,请更改css属性.
First of all, sorry if this is a simple question. I am new to jQuery and I want to know how can I check if an element exists and if it does, change the css property.
这是我的意思:我有以下列表:
Here is what I mean: I have the following list:
<ul class="element-rendered">
<li class="element-choice">Item A</li>
<li class="select-inline">Item B</li>
</ul>
我想知道如何检查element-rendered
中是否存在类select-inline
,如果存在,如何将element-choice
的css背景更改为蓝色?
I want to know how can I check if the class select-inline
exists inside element-rendered
and if it does, how can I change the css background of element-choice
to blue?
我创建了 小提琴 以重现此示例.
I created a fiddle to reproduce this example.
如果这是一个简单的问题,请再次表示歉意,但我是jQuery的新手.
Again sorry if this is a simple question but I am new to jQuery.
推荐答案
您可以使用.length
来检查DOM中是否存在该元素.
You can use .length
to check if the element exists in DOM.
$('.element-rendered .select-inline')
将在具有类element-rendered
的元素内选择所有具有类select-inline
的元素.选择器上的.length
将返回匹配元素的数量.因此,数字大于1表示元素存在.然后,您可以使用.css
设置内联样式.
$('.element-rendered .select-inline')
will select all the elements having class select-inline
inside the element with class element-rendered
. .length
on selector will return the number of matched elements. So, number greater that one, means the element exists. Then you can use .css
to set inline styles.
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
将其添加到元素中.
I'll also recommend you to use class in CSS and add it to the element by using addClass
.
这篇关于jQuery:如何检查元素是否存在并更改css属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!