Java HTML Jsoup Element findFirstByTag(Element element, String tag)

Here you can find the source of findFirstByTag(Element element, String tag)

Description

Returns the first element found with the given tag (or tag sequence separated by '/') or null.

License

Mozilla Public License

Declaration

public static Element findFirstByTag(Element element, String tag) 

Method Source Code

//package com.java2s;
/**//from  www.  j a v a 2 s. co  m
 * Copyright (C) 2012-2014 Gist Labs, LLC. (http://gistlabs.com)
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Main {
    /** Returns the first element found with the given tag (or tag sequence separated by '/') or null. */
    public static Element findFirstByTag(Element element, String tag) {
        return findFirstByTag(element, tag.split("/"), 0);
    }

    private static Element findFirstByTag(Element current, String[] tags, int index) {
        if (index < tags.length) {
            Elements elements = current.getElementsByTag(tags[index]);
            for (Element element : elements) {
                Element result = findFirstByTag(element, tags, index + 1);
                if (result != null)
                    return result;
            }
            return null;
        } else
            return current;
    }
}

Related

  1. extractTextWithNewlines(Element elem)
  2. filterElementsByTag(List results, Element element, Set tagSet)
  3. findAElementsWithId(Elements elements, String id)
  4. findAllNodesBefore(Element firstChapter)
  5. findElementsByTag(Element element, String... tags)
  6. findNextElementSibling(final Element startElement, final Predicate condition)
  7. findPreviousH2Element(Element h3)
  8. findPreviousHElement(Elements sequence, Element reference)
  9. findRootElement(Element element)