0

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>
2
  • 2
    this.style is not a text , it is an object. You must use your debugger by yourself first Commented Feb 15, 2020 at 14:50
  • 1
    Why not += instead of =? Commented Feb 15, 2020 at 14:53

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.