Search code examples
javahtmldomjsoupparent

Jsoup: How to select direct parents until the root without their siblings?


I'm trying to get all direct parents of element, but also I get their siblings.

For example, I have this DOM structure...

<div class="html">
  <div class="head"></div>
  <div class="body">
    <a href="seznam.cz">seznam</a>
    <h2>Foo</h2> 
    <a href="google.com">google</a> 
    <p>
      <img class="first">
    </p>
    <img class="second"> 
    <ol>
      <li>1</li>
      <li>2</li>
    </ol>
  </div>
</div>

So I want get all direct parents of img element with class first until a div with class html.

I've tried using the following code

Element element = document.select("img").first();
Node root = element.root();

But in the root var I get whole DOM structure also with all siblings.

UPDATE

After this in root var I have the whole DOM structure again:

<div class="html">
  <div class="head"></div>
  <div class="body">
    <a href="seznam.cz">seznam</a>
    <h2>Foo</h2> 
    <a href="google.com">google</a> 
    <p>
      <img class="first">
    </p>
    <img class="second"> 
    <ol>
      <li>1</li>
      <li>2</li>
    </ol>
  </div>
</div>

But I want something like this:

<div class="html">
  <div class="body"> 
    <p>
      <img class="first">
    </p>
  </div>
</div>

Solution

  • If you are interested in path only, use Element.cssSelector()

    It gives you whole DOM path e.g. html > body > img

    "Path" returned by Darshit Chokshi approach is not unique.