0

As said above, I want to have JS cycle through textDecoration as I click on a span. I found a fragment of this in another answer that I cannot find anymore and (tried to) modify it.

HTML

<div id="container">
            <span>A</span> <span>B</span> <span>C</span> <span>D</span> 
        </div>

JS

var container = document.getElementById("container");
if (container.addEventListener) {
    container.addEventListener('click', clickHandler, false);
}
else if (container.attachEvent) {
    container.attachEvent('onclick', function(e) {
        return clickHandler.call(container, e || window.event);
    });
}

function clickHandler(event) {
    var span = event.target;
    if (span.style.textDecoration == 'none') {
        span.style.textDecoration = 'underline'
    }
    else if (span.style.textDecoration == 'underline') {
        span.style.textDecoration = 'line-through'
    }
    else if (span.style.textDecoration == 'line-through') {
        span.style.textDecoration = 'none'
    }
}

I think the issue is with using span as the object, but I am not sure how to do it more correctly.

Dave
  • 11
  • 1
  • 5

2 Answers2

0

The reason is because of this:

Element.style returns the inline style used in HTML document and since the style is not set directly in HTML you will get an empty value

So, I have set it to none in the starting. Then it will work. Check out this to see why

var container = document.getElementById("container");
var spans = document.querySelectorAll('span')
for (let i = 0; i < spans.length; i++) {
   spans[i].style.textDecoration = "none" // setting default
}

container.addEventListener('click', function(e) {
    clickHandler(e)
});

function clickHandler(event) {
    var span = event.target;
    if (span.style.textDecoration == 'none') {
        span.style.textDecoration = 'underline'
    }
    else if (span.style.textDecoration == 'underline') {
        span.style.textDecoration = 'line-through'
    }
    else if (span.style.textDecoration == 'line-through') {
        span.style.textDecoration = 'none'
    }
}
<div id="container">
      <span>A</span><span>B</span><span>C</span><span>D</span> 
</div>
codeR developR
  • 468
  • 3
  • 13
0

Try using

span.style.textDecoration == ''

instead of

span.style.textDecoration == 'none'

Also assigning:

span.style.textDecoration = ''

instead of

span.style.textDecoration = 'none'