Reputation: 925
Through a database process I end up with html that contains "spans" that are colored. For example:
<div id="RelevantDiv">the industry's standard <span style="background-color: red">dummy text ever since the 1500s, when an unknown printer took a galley</span> of type and scrambled it to make a type specimen book. It has survived not only five.</div>
Generally I want to retain this coloring. However, I also want to build a javascript function that toggles this background color on or off. I have tried the following:
function HLtoggle()
{
var element = document.getElementById('RelevantDiv');
element.style.background = '#FFFFFF';
}
However, this doesn't work because the span's are obviously overwriding the
Upvotes: 0
Views: 31
Reputation: 28239
Your background-color
is on the span element while in the js your are targetting the parent div
.
Try the following :
var element = document.querySelectorAll('#RelevantDiv > span')[0];
element.style['background-color'] = '#FFFFFF';
Although, I suggest you to give a class name to your highlighted span, and select by that class and not by the tag name.
Upvotes: 1
Reputation: 568
You're pointing at the div, not the span so the css isn't overridden. Try this:
<div id="RelevantDiv">the industry's standard <span id='span_id' style="background-color: red">...
Then change the function
function HLtoggle()
{
var element = document.getElementById('span_id');
element.style.backgroundColor = '#FFFFFF';
}
HLtoggle()
Upvotes: 0
Reputation: 5343
In general to change the color on a span you can use
var element = document.getElementById('RelevantDiv');
element.style.background = '#FFFFFF';
I assume,you want to target the span and not the whole div thus, put the id on span like this
<span id="RelevantDiv" style="background-color: red">
Now to wrap it up in a function you wrote it correctly in the code provided but you need to call that function usually by using an event handler if you want to call it at certain times.
Here is a jsfiddle for calling the function when you mouse over the span.
https://jsfiddle.net/oLfyx0h5/4/
Upvotes: 0