www.webdeveloper.com
Results 1 to 2 of 2

Thread: 2 IDs for getElementById?

  1. #1
    Join Date
    Feb 2011
    Posts
    2

    2 IDs for getElementById?

    I've added a second (mobile)menu to a Wordpress theme, it works fine, but I know I could of done better with the javascript. I've very new to javascript.

    Basically I need to add a second ID to getElementById

    to get around this, I've just copied the entire js and changed the ID and pasted it at the end of the file. I'm sure there is a better way to do this.

    This is the section I need to change the 'site-navigation' part, I need it to also include 'lower-navigation'

    Code:
    var button = document.getElementById( 'site-navigation' ).getElementsByTagName( 'h3' )[0],
    	    menu   = document.getElementById( 'site-navigation' ).getElementsByTagName( 'ul' )[0];
    Here is the full .js file http://pastebin.com/PmAsjUg7

  2. #2
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    881
    The ID attribute for elements is meant to be a unique identifier. Because of that the getElementById() method can only ever return one value. If you of course have duplicate ID values it will cause an error.

    Typically, when you need JavaScript to select multiple elements you will want to use getElementsByTagName() instead and select the correct objects in the array that you would need for your script. Though this can be tricky at times and so there is another option which is getElementsByClassName(). The downside is that this function is new (part of HTML5 if I recall correctly) and so it won't be supported in older browsers and possibly some mobile ones (given your site seems to be designed with that as a target as well).

    If you choose to use this, you can of course specify a class that is purely used for the purpose of identifying the elements in JavaScript (assuming your current classes won't work in to this well). If not then there is likely another work around but would be a little more 'messy' and I'd have to sit down and plan out the code. I suppose let me know what you intend to do from here and I'll see if I can be of any further help.
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

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