Search code examples
javascriptjqueryfirefox-3

jQuery each tr.children is undefined in Firefox 3.0


I have a snippet of code that I'm working with to filter rows in a table. It works perfectly in every browser other than Firefox v3.0.x (works fine with 3.1 beta 2). When I run the snippet in Firefox 3.0.x, it says that children is undefined. I am using jQuery v1.2.6 also.

Code Snippet:

var bodyRows = $("#resultsTable tbody tr");
bodyRows.each(function(n){
    if(!filterPattern.test($.trim(this.children[2].innerHTML))){ //errors here
            this.style.display = 'none';
    }
    else {
            this.style.display = '';
    }
});

The code selects all table rows and then loops through them, testing the innerHTML text of the 3rd column. If the RegEx test fails, the row is hidden, else it is displayed.

Has anyone seen this issue and / or know how to get it working?

Thanks

EDIT: Here is the HTML markup for the table. For brevity, I'm only giving 2 record in it though more are populated.

<table id="resultsTable" cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th>First</th>
                <th>Last</th>
            <th>City</th>
            <th>State</th>
            <th>Zip</th>
            <th>Email</th>
            <th>&nbsp;</th>
        </tr>
    </thead>    
    <tbody id="resultsBody">
        <tr>
            <th>James</th>
                <th>Eggers</th>
            <th>SomeCity</th>
            <th>IA</th>
            <th>55555</th>
            <th>email@email.com</th>
            <th>&nbsp;</th>
        </tr>
        <tr>
            <th>John</th>
                <th>Doe</th>
            <th>SomeCity</th>
            <th>KY</th>
            <th>88888</th>
            <th>email2@email.com</th>
            <th>&nbsp;</th>
        </tr>
    </tbody>        
</table>

Solution

  • Why not use jQuery to traverse the DOM elements instead.

    var bodyRows = $("#resultsTable tbody tr");
    bodyRows.each(function(){
        var thirdCell = $(this).find('td').eq(2);
        if(!filterPattern.test($.trim(thirdCell.html()))){
            this.style.display = 'none';
        } else {
            this.style.display = '';
        }
    });
    

    You could also use '.text()' if you just want the text without any possible markup to be returned.

    The property children is an IE only DOM property which no other browser has (to my knowledge). Firefox uses the standard property childNodes for accessing children. The problem with childNodes is that it considers whitespace and text to be a node (or at least Firebug says so) which makes it (in my opinion) very difficult to deal with. If you have a JavaScript API, you should take advantage of it so that you don't have to deal with the differences between browsers' DOM traversal techniques.