How to find 2 checkboxes on a web page



  • That's easy... just look at EVERY element on the page and only do something if it's a checkbox.  Heck, there's only 5000+ elements, how long could that possibly take? 

    for (iCount=0;iCount<=document.all.length;iCount++) {
        elm = document.all[iCount];
        if (elm.type == 'checkbox') {
            // snip
        }
    }



  • @chortlehoort said:

    Heck, there's only 5000+ elements, how long could that possibly take?

    About half a millisecond 



  • Not at the youtube 0.1 thread.



  • To put it more clearly, the browser will iterate the 5000 elements many times over, doing CPU intensive stuff on each: load them, parse them, render them, resize them, ... One extra pass of 5000 string comparisons won't make noticeable difference.

    That doesn't mean the code snippet isn't a WTF : using document.getElementsByTagName("input") instead of document.all (which is IE-script, not JavaScript) would be a good start to improve it



  • Using IDs for accessing dom elements via javascript is usually the route I go. If I remember correctly, getting a dom element by  document.getElementById('id') is  typically faster than  document.getElementsByTagName("input"),  and returns one object, instead of an array of them.  $0.02 deposited...



  • @kaamoss said:

    Using IDs for accessing dom elements via javascript is usually the route I go.

    True, but there are cases where you have no knowledge about the HTML, its elements and their id, if any, in particular when you make generic JS.



  • @JvdL said:

    @kaamoss said:

    Using IDs for accessing dom elements via javascript is usually the route I go.

    True, but there are cases where you have no knowledge about the HTML, its elements and their id, if any, in particular when you make generic JS.

    That's a good point, I guess I'm so used to not reusing that type of javascript code becase I can type it in emacs faster than I can think what I want it to do. For my code reuse, I try to pull out useful code into custom moo tool classes. Moo tools also gives a short_cut/cross browser way of accessing any dom element you want. I personally think that jQuery is better for this, but moo tools animations/ajax classes just seem to work better for me. If you're consistently writing js you're shooting yourself in the foot not leveraging some kind of js framework. 



  • This page has only 600+ elements. The average corp site -- that I build anyway -- has in the range of 100-200.

    What kind of utterly insane page has five thousand elements?

    (not including the Youtube 0.1 thread, which is accepted as being INSANE YAY)


Log in to reply