Home > Software design >  Set CSS property with pure JS, display:none
Set CSS property with pure JS, display:none

Time:11-21

I have to hide a <section> in my HTML with JavaScript while I am highlighting text, and 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' do not works as others hundred of tried that I have done.

Someone can save my life??

Every setAttribute, style.innerHTML, ecc..

CodePudding user response:

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')
            }
        }
    })

CodePudding user response:

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;'); });
      }

})
  • Related