简体   繁体   中英

How to apply CSS on parent using its child

Hello I want to apply CSS on parent using its child

<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.

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.

How can I hide parent li using child.Is it Possible.

Use .closest() function. 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()

  1. Begins with the current element
  2. Travels up the DOM tree until it finds a match for the supplied selector
  3. The returned jQuery object contains zero or one element for each element in the original set

.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; 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

You can apply .parents() OR .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'});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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