Results 1 to 3 of 3

Thread: Getting multiple ID items from the page.

  1. #1
    Join Date
    Jun 2008
    Posts
    5
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Getting multiple ID items from the page.

    Hi there,

    I am trying to find a javascript code using which I can access multiple elements through their ID. I know it has to be using document.getElementByID and using loops...

    Thanks a lot for the help

  2. #2
    Join Date
    Sep 2005
    Location
    India
    Posts
    1,627
    Thanks
    6
    Thanked 107 Times in 107 Posts

    Default

    Here is one function. Use it instead of using document.getElementById in whereever you need it.

    Code:
    function get(el) {
        if (el) {
            if (typeof el === ’string’) {
                return document.getElementById(el);
            }
            if (typeof el === ‘object’ && el.length && el.length > 0) {
                var els = [];
                for (var i = 0; i < el.length; ++i) {
    		el[i].nodeType !== undefined ? els.push(el[i]) : els.push(document.getElementById(el[i]));
                }
                return els;
            }
            if (typeof el === ‘object’ && el.nodeType !== undefined) {
                return el;
            }
        }
    }
    Usage

    Code:
    var el = get(’myid’); //For retrieving single element, returns the element itself if it found.
    var els = get(['myid1','myid2']);//For retrieving multiple elements, returns an array.
    Please let me know if you need any assistance with the usage.

    Hope this helps.
    Last edited by codeexploiter; 02-24-2009 at 12:20 PM. Reason: Inserted code blocks

  3. The Following User Says Thank You to codeexploiter For This Useful Post:

    jsnewbie (02-24-2009)

  4. #3
    Join Date
    Jun 2008
    Posts
    5
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default

    I'll try this and let you know about the issues, if any.

Bookmarks

Posting Permissions

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