SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    add a class to a tag

    Hi,

    I'm wondering what is the safest way (in terms of cross-browsers issues) to add a class to an element.


  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,683
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by rhgiant View Post
    Hi,

    I'm wondering what is the safest way (in terms of cross-browsers issues) to add a class to an element.

    JavaScript is a higher-level language above those that use classes.

    If this is about CSS classes though, the simplest way is to add a space then your class name.
    You can perform some checks beforehand too to see if the class name is already on the element.

    The code at the following location provides some fairly good ways of doing that.
    http://snipplr.com/view/3561/addclas...lass-hasclass/
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Member
    Join Date
    Jan 2012
    Location
    United States
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Assuming you're talking about CSS classes, you could for example add the "hilite" class to the element represented by the object e, as follows:
    Code:
    if (!e.className)
      /* 'class' attribute contains no other class names: */
      e.className = "hilite";
    else
      /* 'class' attribute already contains one or more class names, so a space separator is needed: */
      e.className += " hilite";

  4. #4
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I was wondering if the snipplr.com snippet would add class if element has no class attribute. Does the element have to already have a class="" or will it automatically add it if none is found?


  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,683
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by rhgiant View Post
    I was wondering if the snipplr.com snippet would add class if element has no class attribute. Does the element have to already have a class="" or will it automatically add it if none is found?
    Yes it will.
    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
  •