0

I'm building a website about laws. Since there're many laws I'd like to show their texts in a div when clicking the names.

   <ul>
      <li><a class="law-link" href="#law1">Law 1</a></li>
      <li><a class="law-link" href="#law2">Law 2</a></li>
      <li><a class="law-link" href="#law3">Law 3</a></li>
      <li><a class="law-link" href="#law4">Law 4</a></li>
      <li><a class="law-link" href="#law5">Law 5</a></li>
      <!-- etc -->
    </ul>
    
   <div class="text">
      <div id="law1" class="law-text">Text of Law 1</div>
      <div id="law2" class="law-text">Text of Law 2</div>
      <div id="law3" class="law-text">Text of Law 3</div>
      <div id="law4" class="law-text">Text of Law 4</div>
      <div id="law5" class="law-text">Text of Law 5</div>
    </div>

I've managed to achieve the desired result with pure CSS:

CSS:

#law1,#law2,#law3,#law4,#law5 { display: none; }

#law1:target {display: block; }
#law2:target {display: block; }
#law3:target {display: block; }
#law4:target {display: block; }
#law5:target {display: block; }

But the problem with my solution is that it's not scalable (there'll be hundreds of laws) and the code looks clunky. Moreover, the biggest problem is that no div is displayed until one of the laws is clicked and I'd like to have at least #law1 displayed by default.

I'm sure plain JavaScript can easily solve the task but my attempt, alas, doesn't seem to be working:

JS:

let legalLinks = document.querySelectorAll('.law-link');
let legalTexts = document.querySelectorAll('.law-text');

legalLinks.forEach((e) => {
  e.addEventListener('click', ()=> {
    e.preventDefault();
    legalTexts[legalLinks.indexOf(e)].style.display = 'block';
  })
});

The idea behind the JS code is: every link (a.law-link) in the array "legalLinks" has the same index as the law (div.law-text) it refers to. Thus, I add an event listener to every link, so that when a link is clicked the display property of its div is set to "block'. But like I said the code isn't working.

I assume the problem is in

legalTexts[legalLinks.indexOf(e)] 

but I don't understand what's wrong with it.

Thank you in advance. With kind regards,

  • 1
    You can use a tag call
    . when you click on it , it will display more info. here is a link for your references https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details This is more manageable when your content grow larger. And you no need javascript to make it work
    – mok_ku Oct 28 '22 at 03:14
  • Thank you. I didn't know that tag. I think it might be useful in my case. – Nickle Sydney Oct 28 '22 at 10:03

0 Answers0