yehuda
yehuda

Reputation: 1282

Why doesnt next() work in jquery

I cannot work out why i cannot pick up the next list item in jquery. However, I can pick up the the span tag after the p tag. Why is this? Please do not just quote me the jquery manual, because I am obviously not understanding it. Thanks in advance.

<ul>
    <li id="one" style="display:block; width: 20px; height: 20px; background: lightgrey; margin:4px;">1<li>
    <li id="two" style="display:block; width: 20px; height: 20px; background: lightgrey; margin:4px;">2<li>
    <li id="three" style="display:block; width: 20px; height: 20px; background: lightgrey; margin:4px;">3<li>
    <li id="four" style="display:block; width: 20px; height: 20px; background: lightgrey; margin:4px;">4<li>
    <li id="five" style="display:block; width: 20px; height: 20px; background: lightgrey; margin:4px;">5<li>
</ul>

<div class="div">
    <p>Hello</p>
    <span>Bye</span>
</div>

My Jquery:

$(function(){
    $('#two').next().css('color','red');
    $('.div p').css('color','red');
});

EDIT: My li tags are not closed. That is causing the problem

Upvotes: 1

Views: 159

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206565

Your li elements are missing the '/' at the end: </li> <-- CORRECT

Upvotes: 2

The Alpha
The Alpha

Reputation: 146239

You didn't close li tags (I've fixed)

<ul>
    <li id="one" style="display:block; width: 20px; height: 20px; background: lightgrey; margin:4px;">1</li>
    <li id="two" style="display:block; width: 20px; height: 20px; background: lightgrey; margin:4px;">2</li>
    <li id="three" style="display:block; width: 20px; height: 20px; background: lightgrey; margin:4px;">3</li>
    <li id="four" style="display:block; width: 20px; height: 20px; background: lightgrey; margin:4px;">4</li>
    <li id="five" style="display:block; width: 20px; height: 20px; background: lightgrey; margin:4px;">5</li>
</ul>

<div class="div">
    <p>Hello</p>
    <span>Bye</span>
</div>​

JS

$(function(){
    $('#two').next().css('color','red');
    $('.div p').css('color','red');
});

DEMO.

Upvotes: 4

Simen Echholt
Simen Echholt

Reputation: 11293

You are not closing your li tags, but opening new ones. Therefore the next li you are selecting is an empty one and not the one that's visible, so you see no result

So you're doing <li>...<li> which ends in (after the browser parses your HTML):

<li id="one">1</li>
<li></li>
<li id="two">2</li>
<li></li>                 <-- this one is selected
<li id="three">3/<li>

Solution is to close the tags correctly <li>...</li>.

Upvotes: 3

Related Questions