AntunCrnja
AntunCrnja

Reputation: 119

Add CSS but keep inline style

What I'm doing wrong.

Need to add CSS with JavaScript but I have to keep all the inline styles.

In this case when user clicks h1 element, the color of the inline style needs to stay the same and just add new style from javascript.

Here is fiddle: https://jsfiddle.net/59qfxwcu/

<h1 style="color: red;">Test</h1>
<h1 style="color: green;">Test</h1>

<script>
function some(){
    var element = document.querySelectorAll('h1');

      element.forEach(function(item){

        item.onclick = function(){
            var inlineCss = this.style;

                item.style.cssText = inlineCss + 'background: blue; font-size: 12px;';
          }

      });
}

some();

</script>

Upvotes: 0

Views: 117

Answers (1)

johannchopin
johannchopin

Reputation: 14844

You need to use style.background and style.fontSize javascript properties:

function some(el) {
  var element = document.querySelectorAll('h1');

  element.forEach(function(item) {

    item.onclick = function() {
      item.style.background = 'blue';  // Change the background of the element
      item.style.fontSize = '12px';    // Change the font-size of the element
    }

  });
}

some();
<h1 style="color: red;">Test</h1>
<h1 style="color: green;">Test</h1>

Upvotes: 1

Related Questions