Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append new attribute with setAttribute()?

Tags:

javascript

dom

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!

like image 500
JSmurf Avatar asked Feb 04 '16 00:02

JSmurf


People also ask

How do I add attributes to querySelector?

JavaScript setAttribute() example How it works: First, select the button with the id btnSend by using the querySelector() method. Second, set the value of the name attribute to send using the setAttribute() method. Third, set the value of the disabled attribute so that when users click the button, it will do nothing.

How do I add attributes in createElement?

To create an element with attributes: Use the document. createElement() method to create the element. Use the setAttribute() method to add one or more attributes to the element.

Does setAttribute overwrite?

Using setAttributeIf the attribute is already assigned to an element, the value is overwritten. If not, elements are assigned a new attribute with indicated values and name.

Why is setAttribute not working?

The "setAttribute is not a function" error occurs for multiple reasons: calling the setAttribute() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. calling the setAttribute method on a jQuery object (should use attr() instead).


2 Answers

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';
like image 117
Bergi Avatar answered Sep 26 '22 14:09

Bergi


Update the style object of the dom-node rather than using setAttribute:

document.getElementById("styled").style["color"] = "red";

More information: http://www.w3schools.com/jsref/dom_obj_style.asp

like image 20
Jonathan.Brink Avatar answered Sep 26 '22 14:09

Jonathan.Brink