jQuery:如何检查元素是否存在并更改css属性 [英] jQuery: How to check if an element exists and change css property

查看:100
本文介绍了jQuery:如何检查元素是否存在并更改css属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,很抱歉,如果这是一个简单的问题.我是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆