Java tutorial
//package com.java2s; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; public class Main { /** * @param n * the node * @return the first element in the ancestor tree of {@code n}. If * {@code n} is an {@link Element}, {@code n} is returned. If * {@code n} is <code>null</code>, this method returns * <code>null</code>. */ public static Element getAncestorElement(Node n) { if (n == null) { return null; } if (n.getNodeType() == Node.ELEMENT_NODE) { return (Element) n; } Node parent = n.getParentNode(); if (parent == null) { Document doc = (Document) (n instanceof Document ? n : n.getOwnerDocument()); return doc == null ? null : doc.getDocumentElement(); } return getAncestorElement(parent); } }