CSS attribute in innerHTML, how to use it?

2

I have span that depending on the value I wanted it to be red for divergence and blue if the data is acceptable, I tried this way:

getElementById('span').css('color', 'blue').innerHTML = <valor>

But this did not work, I saw in the documentation something like style

getElementById('span').style.color = "blue" //nesse caso como recupero o valor?

I also could not use it, I did not want to use css. Is there any way to apply this effect?

    
asked by anonymous 22.05.2017 / 20:57

1 answer

3

You must choose whether to use the jQuery or native JavaScript API. With jQuery you can pass a function in the second argument of the .css() method and give the value depending on the html of the element. It would look something like this:

$('span').css('color', function() {
  return this.innerHTML == 'A' ? 'blue' : 'red';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><span>A</span><span>B</span>

WithnativeJavaScriptyouhavetoseparateinmoresteps:

var spans = [].slice.call(document.querySelectorAll('span'));
spans.forEach(function(span) {
  span.style.color = span.innerHTML == 'A' ? 'blue' : 'red';
});
<span>A</span>
<span>B</span>
    
22.05.2017 / 21:01