SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Aug 2008
    Location
    Taiwan
    Posts
    59
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    concat() doesn't work

    The following code does not work. Is it something wrong?


    Code HTML4Strict:
    <html>
    <body>
     
    <div></div>
    <div></div>
    <div></div>
    <span></span>
    <span></span>
     
     
    <script type="text/javascript">
     
    var i = document.getElementsByTagName("div");
    var j = document.getElementsByTagName("span");
    i = i.concat(j) ;
     
    alert(i.length);
     
    </script>
     
     
    </body>
    </html>

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    That's because concat() is an Array method. i and j are not arrays, they are HTML Collections, which are objects that are "array-like" (you can loop through them, they have a length) but are not arrays (they don't share many of the methods and properties arrays have).

    If' you really need them in a single collection, create an empty array and then loop through i and j, copying the items into your array.

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,527
    Mentioned
    84 Post(s)
    Tagged
    4 Thread(s)
    You can also convert the array-like collection in to actual arrays by using splice, before performing the concat.

    Something like the following should do the trick.

    Code javascript:
    var i = document.getElementsByTagName("div");
    i = Array.prototype.splice.call(i, 0, 0);
     
    var j = document.getElementsByTagName("span");
    j = Array.prototype.splice.call(j, 0, 0);
     
    i = i.concat(j);
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    SitePoint Enthusiast
    Join Date
    Aug 2008
    Location
    Taiwan
    Posts
    59
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I see. Thanks Raffles and pmw57!


Tags for this Thread

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
  •