SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    227
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Directly add an attribute as an element property

    Here's how I change the value of an existing attribute:

    Code:
    element.attribute = "value"
    But is it OK to use the above method to create a new attribute?

  2. #2
    SitePoint Enthusiast
    Join Date
    Sep 2013
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could use:

    Code:
    document.getElementById("element").setAttribute("name", "content");

  3. #3
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,045
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    AFAIK one is (normally) a shortcut for the other.

    E.g.

    Code:
    element.attribute = "value"
    is the same as:

    Code:
    element.setAttribute(attribute, "value");
    So I would say yes, it's fine to use the first method to create a new attribute.

  4. #4
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    227
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    AFAIK one is (normally) a shortcut for the other.

    E.g.

    Code:
    element.attribute = "value"
    is the same as:

    Code:
    element.setAttribute(attribute, "value");
    So I would say yes, it's fine to use the first method to create a new attribute.
    Thanks for the confirmation!

  5. #5
    SitePoint Wizard Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,283
    Mentioned
    51 Post(s)
    Tagged
    2 Thread(s)
    Just the usual warnings about old IE, if you're supporting, being safer with the pure dot (.) notation. Specifically IE up to 8 (and totally not sure what's been fixed in 9) had trouble with both getAttribute and setAttribute. Which is why there's lots of code floating around out there with just .attribute. Or why some people will load up the whole of jQuery just to get el.attr('some attr);

  6. #6
    SitePoint Addict
    Join Date
    Dec 2010
    Posts
    227
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Stomme poes View Post
    if you're supporting
    I'm not. Thanks for the advice, though!


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
  •