Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add css attribute to element

I want to add CSS attributes to my element, but my current solution loses all previous attributes that had an impact on the element.

function checkNr(id) {   var value = document.getElementById(id).value;   if (parseFloat(value) == NaN) {     document.getElementById(id).setAttribute("style", "border:2px solid red; background-color: rgb(255, 125, 115);");   }   else {     document.getElementById(id).setAttribute("style", "border:default; background-color: rgb(255, 255, 255);");   } } 

Before using this method the element already had the attributes:

float: left; width: 50px; 

Afterwards, the element loses these attributes, leaving only the specific attributes from the JavaScript method. So, I want to add attributes without replacing them.

like image 771
Daniel Gustafsson Avatar asked Jul 25 '13 12:07

Daniel Gustafsson


People also ask

Can I add attribute with CSS?

attr() Note: The attr() function can be used with any CSS property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse. The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet.


2 Answers

Setting the style attribute like that, overwrites the attribute and removes previously set styles.

What you really should do is set the styles directly instead by changing the style property :

function checkNr(id) {     var elem  = document.getElementById(id),         value = elem.value;     if (parseFloat(value) == NaN) {         elem.style.border = '2px solid red';          elem.style.backgroundColor = 'rgb(255, 125, 115)';     } else {         elem.style.border = 'none';          elem.style.backgroundColor = 'rgb(255, 255, 255)';     } } 
like image 127
adeneo Avatar answered Oct 01 '22 11:10

adeneo


function checkNr(id) {     var elem = document.getElementById(id);     var css = {};     if (parseFloat(elem.value) == NaN) {         css = { border: '2px solid red', backgroundColor: 'rgb(255, 125, 115)' };     } else {         css = { border: 'none', backgroundColor: 'rgb(255, 255, 255)' };     }      Object.assign(elem.style, css); } 
like image 44
Fatih Ertuğral Avatar answered Oct 01 '22 13:10

Fatih Ertuğral