How can I append style element to DOM without eliminating existing style on the item (eg color, text-align, etc)?
The event calls the function, but the problem is ‘Style’ gets completely replaced with the single item instead.
I have simple code triggered on the event:
JavaScript
x
7
1
function changeback(onoff) {
2
if(onoff) {
3
document.getElementById("field1").style.background="#fff";
4
} else
5
document.getElementById("field1").style.background="#000";
6
}
7
Advertisement
Answer
Which browser are you using? In Chrome, this works for me:
JavaScript
1
22
22
1
<html>
2
<head>
3
<style type="text/css">
4
.test { background: #ff0000; font-family: "Verdana"; }
5
</style>
6
<script type="text/javascript">
7
function changeback(onoff)
8
{
9
if(onoff){
10
document.getElementById("field1").style.background="#0f0";
11
} else {
12
document.getElementById("field1").style.background="#000";
13
}
14
}
15
</script>
16
</head>
17
<body>
18
<h1>Test</h1>
19
<p id="field1" onclick="changeback(true);" class="test">This is a test</p>
20
</body>
21
</html>
22
When I click on the text, the background color changes, but the rest of the style (in this case, the font) stays the same.
Is that what you’re trying to do?