views:

3450

answers:

3

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.

+4  A: 

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.

annakata
this is something of my own. basically i need a way to set a flag on an element....something like div.thisDivIsSet = true;
dev.e.loper
edited into answer
annakata
+3  A: 

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' );
tvanfosson
+2  A: 

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.

andi
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'
dev.e.loper