That's what I was hoping for, but next() and prev() act on the next
and previous elements in the DOM, not in the nodes you're looping
over. To demonstrate:

$("p").each(function(i) {
        console.info($(this).next().html());
        console.info($(this).prev().html());
});

<form action="test.cfm" method="post">
        <div>
                <p>1</p>
                <div>
                        <p>This is next</p>
                </div>
        </div>
        <div>
                <div>
                        <p>This is previous</p>
                </div>
                <p>2</p>
        </div>
        <div>
                <p>3</p>
        </div>
</form>

Maybe I have to come out to the outer most divs before calling next()/
prev() on it.

Adrian

On Feb 4, 4:16 pm, Stephan Veigl <stephan.ve...@gmail.com> wrote:
> Hi,
>
> there are prev() and next() functions doing exactly what you need:
>
> $("div").each( function() {
>   var prev = $(this).prev();
>   var next = $(this).next();
>   alert( prev.text() + "-" + next.text() );
>
> });
>
> (I've skipped the extra code for the first and last element for simplicity.)
>
> by(e)
> Stephan
>
> 2009/2/4AdrianLynch<adely...@googlemail.com>:
>
>
>
> > Hey all, I'm loop over some nodes witheach() and I need to look at
> > the next and previous elements for the current iteration.
>
> > <script type="text/javascript">
> >        $(function() {
> >                $("div").each(function(i) {
> >                        var prev = [SELECTOR FOR PREVIOUS DIV].text();
> >                        var next = [SELECTOR FOR NEXT DIV].text();
> >                        alert(prev + " : " + next);
> >                });
> >        });
> > </script>
>
> > <div>1</div>
> > <div>2</div>
> > <div>3</div>
>
> > Will I have to store a reference to the divs and access it with i in
> > the loop like this:
>
> > <script type="text/javascript">
> >        $(function() {
>
> >                var divs = $("div");
>
> >                divs.each(function(i) {
>
> >                        var prev = "";
> >                        var next = "";
>
> >                        if (i > 0)
> >                                prev = $(divs.get(i - 1)).text();
>
> >                        if (i < divs.size() - 1)
> >                                next = $(divs.get(i + 1)).text();
>
> >                        alert(prev + " - " + next);
>
> >                });
> >        });
> > </script>
>
> > <div>1</div>
> > <span>Spanner in the works</span>
> > <div>2</div>
> > <span>Don't select me!</span>
> > <div>3</div>
>
> > Is next() the answer maybe?

Reply via email to