1

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.

0x269
  • 688
  • 8
  • 20
  • 1
    Relevant: [What do querySelectorAll and getElementsBy* methods return?](https://stackoverflow.com/q/10693845) – VLAZ Nov 20 '22 at 10:30

2 Answers2

0

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

})
Usitha Indeewara
  • 870
  • 3
  • 10
  • 21
0

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