www.webdeveloper.com
Results 1 to 4 of 4

Thread: Custom function to get real first child element

  1. #1
    Join Date
    Dec 2010
    Location
    Brazil
    Posts
    32

    Custom function to get real first child element

    Code:
        function FCE(e) { // {{{
            /* First Child Element - only tags, not text. */
            e = e.firstChild;
            do {
                e = e.nextSibling;
            } while (e && e.nodeType != 1);
            return e;
        } // }}}
         
        window.onload = function() {
            var li = document.getElementsByTagName('li');
            for (var i = 0; i < li['length']; i++) {
                console.log(li[i]); // Outputs <li>
                console.log(li[i].firstChild); // Outputs <a href=...'>
                console.log(FCE(li[i])); // Outpus null.
            }
        };
    The html is the traditional
    Code:
    <li><a href='...>text</a></li>
    I just can't understand what is wrong with the line
    Code:
    console.log(FCE(li[i]));
    Why is it returning null? The two lines above do return what is supposed to be returned, and I used them just as a test.

    Also, the reason why I am trying the custom FCE(e) function, is that I want to be sure that the real first child element will be returned, and not, for instance, a text node or a "white space" node.

    Any help would be appreciated.

  2. #2
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,276
    Simply <a href=...</a> has not sibling !

  3. #3
    Join Date
    Dec 2010
    Location
    Brazil
    Posts
    32
    Quote Originally Posted by 007Julien View Post
    Simply <a href=...</a> has not sibling !
    But my funcion only tries finding a sibling if the element the first child itself is different than nodeType 1:

    Code:
     e = e.firstChild;
            do {
                e = e.nextSibling;
            } while (e && e.nodeType != 1);
            return e;
    If e is already type 1, e = e.nextSibling won't even run. The first child of <li> is <a>, but in my html I have some lines in which the <a> is after a newline character. That is why I'm trying to find the real first child.

  4. #4
    Join Date
    Mar 2011
    Posts
    61
    You should use a 'while' loop instead of a 'do while' loop. The 'do while' will execute the code block once, before testing the condition.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles