5

I have searched around I cannot find a way to do this. I have a group of elements. I select one element from this group. How could I find the next element after this selected element?

superuser
  • 701
  • 10
  • 28

1 Answers1

15

Use the method nextElementSibling().

Example:

<body>
    <p>First in family!</p>
    <p>Second in family!</p>
    <p>Third in family!</p>
</body>

Jsoup:

Element firstParagraph = doc.select("p:eq(0)").first();
Element secondParagraph = firstParagraph.nextElementSibling();

System.out.println(firstParagraph.text() + " " + secondParagraph.text());

Output: First in family! Second in family!

kubuntu
  • 2,515
  • 1
  • 21
  • 24
Daniel B
  • 8,492
  • 5
  • 44
  • 74
  • Thanks for the answer! I am getting a null pointer exception when I call .nextElementSibling – superuser Oct 16 '13 at 22:17
  • What is your stacktrace? I hadn't run the code when I posted the answer, but when I tried it now it works perfectly, except that you might want to add .text() to just get the text instead of the complete

    -tag!

    – Daniel B Oct 16 '13 at 22:29
  • How to get next in selector syntax? –  Oct 05 '18 at 05:48