Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
7.1k views
in Technique[技术] by (71.8m points)

How to select the divs with the same class name using the jQuery?

I have this code, I am trying to add an additional class "active" to all of the elements with the same class inside the experts-list div.

I want if someone clicks on the heading Athletes then an additional class "active" should be applied on Athlete One, Athlete Two, Athlete Three, and Athlete Four

and same with the other elements

<div class="expert-group-titles">
    <h3 class="athlete">Athletes</h3>
    <h3 class="actor">Actors</h3>
    <h3 class="business-man">Business Men</h3>
    <h3 class="chef">Chefs</h3>
    <h3 class="comedian">Comedians</h3>
    and list goes on...
</div>
<div class="experts-list">
    <div class="expert-box athlete">Athlete One</div>
    <div class="expert-box athlete">Athlete Two</div>
    <div class="expert-box athlete">Athlete Three</div>
    <div class="expert-box athlete">Athlete Four</div>
    <div class="expert-box actor">Actor One</div>
    <div class="expert-box actor">Actor Two</div>
    <div class="expert-box actor">Actor Three</div>
    <div class="expert-box actor">Actor Four</div>
    <div class="expert-box business-man">Business Man One</div>
    <div class="expert-box business-man">Business Man Two</div>
    <div class="expert-box business-man">Business Man Three</div>
    <div class="expert-box business-man">Business Man Four</div>
    <div class="expert-box chef">Chef One</div>
    <div class="expert-box chef">Chef Two</div>
    <div class="expert-box chef">Chef Three</div>
    <div class="expert-box chef">Chef Four</div>
    <div class="expert-box comedian">Comedian One</div>
    <div class="expert-box comedian">Comedian Two</div>
    <div class="expert-box comedian">Comedian Three</div>
    <div class="expert-box comedian">Comedian Four</div>
    and list goes one...
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. This line of code will select all the elements with these two classes

    var athletes = jQuery('.expert-box.athlete')

  2. Now you can add a specific class to the athletes

    athletes.addClass('active')


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
...