Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Jul 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    What's the correct way to set an attribute on a DOM object?

    Which of these is the correct way to set the className attribute, or are they both okay?

    option 1:
    Code:
    var t = document.createElement("p");
    t.className = "myclass";
    option 2:
    Code:
    var t = document.createElement("p");
    t.setAttribute("class","myclass");

  • #2
    Regular Coder
    Join Date
    Jan 2006
    Posts
    568
    Thanks
    6
    Thanked 84 Times in 84 Posts
    Both are OK, but .className is more cross browser compatible. I'm not sure how far back support in Internet Explorer goes, but to be on the safe side I would generally stick to dot/square bracket syntax.

  • #3
    New to the CF scene
    Join Date
    Jul 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    good to know. Thanks.

  • #4
    New Coder
    Join Date
    Jul 2010
    Posts
    61
    Thanks
    0
    Thanked 21 Times in 21 Posts
    Never use setAttibute unless direct assignment fails, and the only time I have encountered that is when setting properties of an <embed> element.

  • #5
    Regular Coder
    Join Date
    Jan 2006
    Posts
    568
    Thanks
    6
    Thanked 84 Times in 84 Posts
    Document objects returned by AJAX calls also use get-/setAttribute.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •