0

I need to acces an element that has a certain style.

This is my structure

<ul>
  <li> Hi </li>
  <li> bye </li>
  <li> third one </li>
</ul>

The list items are placed on top of each other (last one first) and I can dislike something or like something. Once I do that, it gets a style display:none like following:

<ul>
  <li> Hi </li>
  <li> bye </li>
  <li style:"display:none;"> third one </li>
</ul>

Now after I did that I want to be able to acces the last element that does not have display:none, (the bye) how can I do this?

I was thinking of something in the form of:

var myId = $("#slider > ul li").last().attr("id");

But obviously I always get the ID of the item that is hidden since its still there.

Can I do something like select last where !display:hidden ?

2
  • 3
    First of: style:"display:none;" should be style="display:none;", secondly: if you add a class instead of a style and then define the display: none in your CSS, you could use $('#slider > ul li:not('.myDeactivatedClassName')') Commented Oct 5, 2015 at 15:33
  • 3
    Use a css class name to both put that certain style on elements and select all elements with that style. Commented Oct 5, 2015 at 15:34

4 Answers 4

3

Can I do something like select last where !display:hidden ?

Yes, with jQuery's :visible pseudo-class:

var myId = $("#slider > ul li:visible").last().attr("id");

(Note: Your li elements don't actually have id values, but that's a tweak.)

Live Example:

var listItem = $("#slider > ul li:visible").last();
$("<p>")
  .text("Text of last visible item: " + listItem.text())
  .appendTo(document.body);
<div id="slider">
  <ul>
    <li>Hi</li>
    <li>bye</li>
    <li style="display:none;">third one</li>
  </ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! Thank you!
2

Can use ':visible' selector

var myId = $("#slider > ul li:visible").last().attr("id");

Comments

0

It should work using:

$("#slider > ul li:visible").last().attr("id");

https://api.jquery.com/visible-selector/

Comments

0

so your inline styling is a bit off it should be

<ul>
  <li> Hi </li>
  <li> bye </li>
  <li style="display:none;"> third one </li>
</ul>

You could do a few different things, best is probably just iterate through and check for where display = none, then go to the previous element:

$('ul').children().each(function(e) {
   if($(this)[0].style.display == 'none') {
     console.log($(this).prev());   
   }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.