SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Wizard bronze trophy PicnicTutorials's Avatar
    Join Date
    Dec 2007
    Location
    Carlsbad, California, United States
    Posts
    3,658
    Mentioned
    15 Post(s)
    Tagged
    0 Thread(s)

    How to condense multiple "document.getElementById" into one statement?

    Code JavaScript:
    <script type="text/javascript">
    document.getElementById('collapse').innerHTML = 'Collapse all';
    document.getElementById('expand').innerHTML = 'Expand all';
    document.getElementById('bar').innerHTML = '|';
    </script>

    Thanks

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    With what you're doing above you can't as there would be no way to set the HTML for each individual element if they would grouped together.

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,871
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    The best you could do to shorten this code would be to create a function so that you can remove the common part of each statement.

    Code:
    set = function (id, txt) {document.getElementById(id).innerHTML = txt;}
    set('collapse','Collapse all');
    set('expand','Expand all');
    set('bar', '|');
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  4. #4
    SitePoint Wizard bronze trophy PicnicTutorials's Avatar
    Join Date
    Dec 2007
    Location
    Carlsbad, California, United States
    Posts
    3,658
    Mentioned
    15 Post(s)
    Tagged
    0 Thread(s)
    Thanks Felgall. Is one way faster than the other? Negligible I know. It's wins on code length.

    document.getElementById('collapse').innerHTML = 'Collapseall';document.getElementById('expand').innerHTML = 'Expandall';document.getElementById('bar').innerHTML = '|';

    set = function (id, txt) {document.getElementById(id).innerHTML = txt;}set('collapse','Collapseall');set('expand','Expandall');set('bar', '|');


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
  •