October 3, 2012

How to replace style with javascript that has already been set?

Question by vusan

I’m implementing menu that is selected by the help of javascript. In jsfiddle.
Blocks are selected by the help of changing the style in innerHTML of div here.

But how to replace the style that has already been set?

Here my problem is I cannot select block 1.

full html code:

<style>
div {width:10px;height:10px;margin:10px;
    background:#ccc;cursor:pointer;padding:10px;
}
</style>
<div id="makeThatEnable" style="display:none"></div>

<div id="one" onclick="makeThisEnable(this.id)" style="border:1px solid #00f">1</div>
<div id="two" onclick="makeThisEnable(this.id)">2</div>
<div id="three" onclick="makeThisEnable(this.id)">3</div>
<div id="four" onclick="makeThisEnable(this.id)">4</div>
<div id="five" onclick="makeThisEnable(this.id)">5</div>
<br>
Click on box to select it.

<script>
function makeThisEnable(id) {
    document.getElementById('makeThatEnable').innerHTML="<style> #"+id+" {border:1px solid #f00}</style>";   
}
</script>

Answer by Starx

I have a better approach.
Uniquely identify a style element like this

<style id="innerStyle">
</style>

Then update your function like this

function makeThisEnable(id) {
    document.getElementById('innerStyle').innerHTML="div#"+id+" {border:1px solid #f00}";   
}

Instead of using !important to force the style, simple increase the specificity of the declaration like I am doing.

DEMO

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!