CSS attribute in innerHTML, how to use?

Asked

Viewed 592 times

2

I have a 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 way it didn’t work, I saw in the documentation something like style

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

I couldn’t use it either, I didn’t want to use css. has some way to apply this effect?

1 answer

4


You have to choose whether to use the jQuery API or native Javascript. With jQuery you can pass a function on second argument of the method .css() and give value depending on the html of the element. It would be 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>

With native Javascript you have to separate in more steps:

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>

  • 1

    thank you saved me again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.