Sunday, April 17, 2011

How to add/update an attribute to an HTML element using javascript?

I'm trying to find a way that will add / update attribute using javascript. I know I can do it with SetAttribute function but that doesn't work in IE.

From stackoverflow
  • What do you want to do with the attribute? Is it an html attribute or something of your own?

    Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.

    For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

    dev.e.loper : this is something of my own. basically i need a way to set a flag on an element....something like div.thisDivIsSet = true;
    annakata : edited into answer
  • Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.

    $('#element').attr( 'title', 'foo' );
    
  • You can read here about the behaviour of attributes in many different browsers, including IE.

    element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, than maybe element.attributeName = 'value' might work.

    dev.e.loper : this works. it creates attribute if it doesn't exists and updates it if it does exist. is this documented somewhere as far as how this works?
    dev.e.loper : by 'this works' i mean element.attributeName = 'value'

0 comments:

Post a Comment