qwerty
qwerty

Reputation: 981

Javascript (jQuery): next() gives me "li.next()" instead of "li"

Confusing title, huh? I tried to explain it as best as i could.

What i mean is, if i have a menu like this:

<ul>
    <li> Home </li>
    <li class="current"> Portfolio </li>
    <li> Store </li>
    <li> About </li>
</ul>

and use the .next() method to get the next element FROM the current one:

$('ul li.current').next()

the result selector is:

ul li.current.next()

instead of a real selector. I mean, i can't target ul li.current.next() with CSS (and therefore it isn't a "real" selector). The real selector would look like ul li.

Is there any way to get the "real" selector of the next element?

Upvotes: 2

Views: 7820

Answers (3)

Tim Hobbs
Tim Hobbs

Reputation: 2017

This works:

$(document).ready(function() {
  var $li = $("ul li.current").next();
  $li.css("font-weight", "bold");
});

Or you can skip the var assignment and access it like this:

$("ul li.current").next().css("text-decoration", "underline");

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816324

If you want the equivalent CSS selector, it would be:

ul li.current + li

See: Adjacent sibling selector

Note: Not supported in IE6.

Also note that jQuery does not use CSS selectors to match all the elements. The selector syntax is just similar (it is a superset) to CSS because it seemed to be the most natural way. It uses methods provided by the browser (e.g. querySelectorAll) where it can but it also has to traverse the DOM in order to find the elements.

E.g. you can never match $('td').closest('tr') with CSS as you cannot "move up" with CSS.

I hope this answers your question, if not please clarify it.

Upvotes: 2

phirschybar
phirschybar

Reputation: 8579

$('ul li.current').next() will simply return the next <li>. It will return

<li> Store </li>

Upvotes: 0

Related Questions