Problem with . find()

Asked

Viewed 47 times

3

I’m trying to find a li with a certain class (selected), however, I haven’t been able to find the id hers.

Here’s the code

var slide_act = $(".bull").find("selected").attr("id");
console.log(slide_act);

On the console appears undefined when I perform the function of click. Any explanation?

Additional Code

<ul class="bullets">
  <li class="bull selected" id="slide1"></li>
  <li class="bull" id="slide2"></li>
  <li class="bull" id="slide3"></li>
</ul>
  • Post the html so we can help you

  • @Caiqueromero Sorry, edited.

  • 1

    because you don’t look right for the class selected thus : var slide_act = $(".selected").attr("id"); ?

  • @Viniciusshiguemori This results as a temporary response, but this class may be associated with other things, so I just wanted to select those that also had the class .bull

  • Also missing a point . in the find("selected")

1 answer

4


You can simply take the "id" attribute of the element that has both the "bull" class and the "Selected" class":

var slide_act = $(".bull.selected").attr("id");

Jquery class selector

See example working:

var slide_act = $(".bull.selected").attr("id");
console.log(slide_act);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul class="bullets">
  <li class="bull selected" id="slide1"></li>
  <li class="bull" id="slide2"></li>
  <li class="bull" id="slide3"></li>
</ul>

  • It worked! I tried with the space in the middle, so: $(".bull .selected") but did not give, could explain?

  • The correct syntax is without the space, I added the documentation in the reply. https://api.jquery.com/class-selector/

  • Is that separate it tries to find the descendant of the class bull that has the class Selected would be for example : <ul class="bullets"><li class="bull" id="slide1"><ul class="selected" id="teste"></ul></li></ul>, already when it is together it looks for the elements that possess both classes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.