简体   繁体   English

如何使用子级在父级上应用CSS

[英]How to apply CSS on parent using its child

Hello I want to apply CSS on parent using its child 您好,我想在使用其子级的父级上应用CSS

<li>
    <div>
        <label>
            <b style="display: none;">Name and Date of Event*: </b>
        </label>
    </div>
</li>

I want to hidden to list. 我想隐藏列表。 but I don'n know how to Apply CSS. 但我不知道如何应用CSS。

I used just 我只是用

jQuery("b:contains('Name and Date of Event*:')").css('display','none');

But it hidden only <b> Tag I want to hide li. 但是它只隐藏<b>标签,我想隐藏li。

How can I hide parent li using child.Is it Possible. 如何使用子项隐藏父级li?

Use .closest() function. 使用.closest()函数。 It accepts a selector and finds the the appropriate ancestor. 它接受选择器并找到适当的祖先。

 $('#btn').on('click', function(){ $("b:contains('Name and Date of Event*:')").parents('li').css('display','none'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li> Li Content <div> <label> <b style="display: none;">Name and Date of Event*: </b> </label> </div> </li> <button id="btn">Hide li</button> 

Why use .closest and not .parents ? 为什么要使用.closest而不使用.parents

.closest() .closest()

  1. Begins with the current element 从当前元素开始
  2. Travels up the DOM tree until it finds a match for the supplied selector 向上移动DOM树,直到找到与提供的选择器匹配的对象
  3. The returned jQuery object contains zero or one element for each element in the original set 返回的jQuery对象在原始集中的每个元素包含零个或一个元素

.parents() 。父母()

  1. Begins with the parent element 从父元素开始
  2. Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; 在DOM树中浏览到文档的根元素,将每个祖先元素添加到一个临时集合中; it then filters that collection based on a selector if one is supplied 然后,如果有选择器,则根据选择器过滤该集合
  3. The returned jQuery object contains zero or more elements for each element in the original set 返回的jQuery对象包含原始集中每个元素的零个或多个元素

You can apply .parents() OR .closest() 您可以应用.parents().closest()

Try this 尝试这个

jQuery("b:contains('Name and Date of Event*:')").parents('li').css('display','none');

OR 要么

jQuery("b:contains('Name and Date of Event*:')").closest('li').css({'display':'none'});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM