Set CSS property with pure JS, display:none

289 Views Asked by At

I need to hide a <section> in my HTML with JavaScript while highlighting the text or to show it otherwise.

My selection works in this way:

document.addEventListener('click', function(){

      var selected = window.getSelection();
      var links = document.getElementsByClassName("linkAnnotation");

      if (selected == '') {
        links.setAttribute('style', 'display:block;');
      } else {
        links.setAttribute('style', 'display:none;');
      }

})

but this setAttribute does not work as other hundreds of tries that I have done.

Can someone save my life??

Every setAttribute, style.innerHTML, etc.

2

There are 2 best solutions below

1
Usitha Indeewara On

getElementsByClassName returns a HTMLCollection (Which returns an array-like object of all child elements which have all of the given class name(s)). You have to iterate through all of those elements and change properties.

So, you have to use the following code:

document.addEventListener('click', function() {

      var selected = window.getSelection();
      var links = document.getElementsByClassName("linkAnnotation");

      if (selected === '') {
        links.forEach(val => { val.setAttribute('style', 'display:block;'); });
      } else {
        links.forEach(val => { val.setAttribute('style', 'display:none;'); });
      }

})
3
Giorgi Shalamberidze On

when you are selecting links it retuns HTMLCollection forExample : [linkAnnotation1, linkAnnotation2] it not returns one element because your code doesnot works you must write for loop example:

document.addEventListener('click', function () {

        var selected = window.getSelection();
        var links = document.getElementsByClassName('linkAnnotation')
        if (selected == '') {
            for (let i = 0; i <= links.length - 1; i++) {
                links[i].setAttribute('style', 'display:block')
            }
        }else {
            for(let i = 0; i <= links.length - 1; i++) {
                links[i].setAttribute('style', 'display:none')
            }
        }
    })