21470 Репутация автора
65396 Репутация автора
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.
446612 Репутация автора
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.
Автор: tvanfosson Размещён: 02.04.2009 03:50
$('#element').attr( 'title', 'foo' );
9133 Репутация автора
359 Репутация автора
What seems easy is actually tricky if you want to be completely compatible.
var e = document.createElement('div');
Let's say you have an id of 'div1' to add.
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).
e['id'] = 'div1'; e.id = 'div1'; e.attributes['id'] = 'div1'; e.createAttribute('id','div1')
But there are contingencies, of course.
Will not work in IE prior to 8:
Will not error but won't actually set the class, it must be className:
However, if you're using attributes then this WILL work:
In summary, think of attributes as literal and object-oriented.
In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.
Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.
It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.
This was longer than I wanted, but CSS manipulation in JS is tricky business.Автор: JPearce Размещён: 24.01.2011 02:41