SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Please help improve my code

    I have this which performs an action on all elements with the class names 'class1' and 'class2'. How would be the better way to code it so I don't just have to repeat the code multiple times (class names don't always have a number after it)?

    var elements = getElementsByClassName(document, 'class1'),
    elementsLength = elements.length,
    i;
    for (i = 0; i < elementsLength; i += 1) {
    // etc.
    }
    var elements = getElementsByClassName(document, 'class2'),
    elementsLength = elements.length,
    i;
    for (i = 0; i < elementsLength; i += 1) {
    // etc.
    }

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by johnsmith153 View Post
    I have this which performs an action on all elements with the class names 'class1' and 'class2'. How would be the better way to code it so I don't just have to repeat the code multiple times (class names don't always have a number after it)?
    The best way would be to use a function, to which you can provide different parameters, and return a different result based on those parameters.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


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
  •