Search code examples
xmldomgetelementsbytagname

Get Child Nodes By Tag Name in DOM


I know that in DOM, the Document object has the method getElementsByTagName().

Why is this operation not defined on any particular Node? Suppose I have a Node object, and I want to find a particular child of that Node by name. Do I really have to implement my own method to traverse all its children until I find the one with that name? (I am not using XPath.) Sounds like a lot of work for a simple task. Thanks


Solution

  • I think you're talking about JAVA. If it's Javascript, foreget this answer (and please tag accordingly your question). In that case, getElementsByTagName only works on "Element" objects, and not on "Node" objects (all Elements are Nodes, but all Nodes are not Elements).

    http://docs.oracle.com/javase/6/docs/api/org/w3c/dom/Element.html

    If you are sure your object is an Element, you can do a cast just before calling the method

    Element eElement = (Element) nNode;
    

    You may need http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#isAssignableFrom%28java.lang.Class%29 before.