Reputation: 1651
I have the following div element
<div style="color:#0000FF">
<h3>This is a heading</h3>
<p>This is a paragraph.</p>
</div>
Is there a way to change the style attribute of this div tag using JavaScript?.
specifically I want to do the following:
Set this style attribute to another string, eg style = "test"
create a new style attribute and replace this attribute with the new attribute
ie:
var new_style_a = document.createAttribute("style");
(somehow insert this new attribute into the div tag)
Upvotes: 3
Views: 1618
Reputation: 2131
You need to get JS to reference your div element by id.
HTML
<div id="elem-change" style="color:#0000FF">
<h3>This is a heading</h3>
<p>This is a paragraph.</p>
</div>
JS
if (document.getElementById("elem-change")) {
document.getElementById("elem-change").style.color = "#0000FF";
}
or
document.getElementById('elem-change').setAttribute('style','color :#0000FF');
JQUERY
$("#elem-change").css("color", "#0000FF");
Upvotes: 0
Reputation: 28387
Is there a way to change the style attribute of this div tag using JavaScript?. specifically I want to do the following: Set this style attribute to another string, eg style = "test"
If you want to replace the existing style attribute (or create one if not existing) on the element, then use:
document.getElementById('elemId').setAttribute('style','width:100px;');
If you want to add a new style property to the existing rules, then it would be like:
document.getElementById('elemId').style.setAttribute('width', '150px');
You need to be able to refer to that div
. Best is to give it a unique id
and use getElementById
to refer that.
Upvotes: 2
Reputation: 3324
You need to get a JS reference to your div first - for simplicity's sake lets just give it an ID for now;
<div id='myDiv' style="color:#0000FF">
<h3>This is a heading</h3>
<p>This is a paragraph.</p>
</div>
Then in JS...
document.getElementById('myDiv').style.color = '#FF0000';
EDIT: To reflect your edited question. If you just want to set the value of an attribute to some string (for the record, not the best way to go if you're doing this to affect the style), you can do;
document.getElementById('myDiv').setAttribute('style','somestring');
EDIT AGAIN; If you insist on using document.createAttribute
...
var attr = document.createAttribute('style');
attr.value = 'somestring';
document.getElementById('myDiv').setAttributeNode(attr);
Upvotes: 4