Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  68] [ 6]  / answers: 1 / hits: 26003  / 8 Years ago, thu, february 4, 2016, 12:00:00

I have a div element and would like to append new style attributes to it.
I have tried to do it like this:



element.setAttribute('style', 'property: value');


And it works, but if that element already had styles applied, they will all get overwritten.



Lets say I have this situation:



HTML:



<div id=styled></div>


JavaScript:



var styled = document.getElementById('styled');
styled.setAttribute('style', 'display: block');


This works, but if I need to append another style lets say:



styled.setAttribute('style', 'color: red');


I would then lose style added in previous setAttribute() method!



How can one append styles to elements with JavaScript?



Thanks!


More From » dom

 Answers
12

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



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


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';

[#63452] Tuesday, February 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marinalyssak

Total Points: 637
Total Questions: 101
Total Answers: 94

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
;