且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用setAttribute()追加新属性?

更新时间:2023-12-05 14:22:10

好吧,如果使用 setAttribute ,则可以通过 getAttribute 并将其合并:

Well, if using setAttribute you could just take the previous value by getAttribute and concat them:

 element.setAttribute('style', element.getAttribute('style')+'; color: red');

但是,这不是大多数HTML属性的***做法,通常将其反映为属性,而您可以做类似 element.className + =… 之类的事情。特别是对于内联样式,您可以使用 .style 属性,可让您设置和取消设置每个CSS属性:

However, that's not the best practise for most HTML attributes, which are usually reflected as a property and you could just do something like element.className += " …". For inline styles in particular, you'd use the .style property that allows you to set and unset every single CSS property:

element.style.display = 'block';
element.style.color = 'red';