SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Zealot
    Join Date
    Dec 2010
    Posts
    179
    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
    5,312
    Mentioned
    177 Post(s)
    Tagged
    8 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 Zealot
    Join Date
    Dec 2010
    Posts
    179
    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
    om nom nom nom Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,233
    Mentioned
    47 Post(s)
    Tagged
    1 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 Zealot
    Join Date
    Dec 2010
    Posts
    179
    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
  •