getting the children

Discussion in 'Javascript' started by Wim Roffal, Sep 18, 2004.

  1. Wim Roffal

    Wim Roffal Guest

    I am having a <div> with <a>s and <div>s inside it.

    I am trying to read in all the elements in the right order.

    With mydiv.getElementsByTagName("a") I can get the elements of a specific
    tag like "a", but I want all types.

    I tried getChildNodes but that doesn't seem to be widely supported.
    childNodes[] seemed to do something but I couldn't get it working when I
    wanted to browse through the elements.

    What is the best way to do this?

    A related question. If I have an element, how can I see which type (a, div,
    input,etc) it is?


    Wim Roffal, Sep 18, 2004
    1. Advertisements

  2. On Sat, 18 Sep 2004 18:39:13 +0200, Wim Roffal

    Probably because it doesn't exist. It's not part of Microsoft's DOM, or
    the standardised W3C DOM (unless it's in Level 3).
    Mind showing what you were trying to do? The childNodes collection is your
    best bet.
    Use the nodeName property. This will return a case-sensitive string with
    the element name. In HTML, the string will always be in uppercase.

    Hope that helps,
    Michael Winter, Sep 18, 2004
    1. Advertisements

  3. Wim Roffal

    Fred Oz Guest

    To help you out, childNodes returns a collection,
    you can do something like:

    var a = document.getElementById('aDiv').childNodes;
    for (var i=0; i<a.length; ++i) {
    // do something to each child

    Other useful methods are firstChild and nextSibling - which is
    really useful if you start at some unknown point in a DOM and
    just want the next sibling. Say you want to find the next one
    after "a" above without having to find the parentNode, work out
    the index of "a", then get the next one. It's all
    done by "var b = a.nextSibling".
    There is also nodeType, but different browsers seem to put
    different node types in some places so it may not be that
    useful for you.

    Cheers, Fred.
    Fred Oz, Sep 19, 2004
  4. [snip]
    The nodeType property doesn't return the information the OP wanted,
    though. It returns quite literally the type: element, comment, DOCTYPE,
    text, etc. However, that information does prove very useful when iterating
    through the tree when looking for generic types. If you're looking for a
    specific element, such as an INPUT, there isn't much need for it.

    Michael Winter, Sep 19, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.