1

I would like to open a modal that shows a pdf according to the selected text, but only the first one in the list is shown. What should I do?

index.html

<p><a id="other-activies-link">Semana Omnistack 11</a></p>
<p><a id="other-activies-link">28ª Semana do IME</a></p>

<div id="myModal" class="modal">
 <div class="modal-content">
  <span class="close">&times;</span>
  <iframe id="myFrame" frameborder="0" allowfullscreen></iframe>
 </div>
</div>

scripts.js

const selectedActivity = document.querySelectorAll("#other-activies-link");

selectedActivity.forEach((link) => {
  link.addEventListener("click", () => {
    document.getElementById(
      "myFrame"
    ).src = `/files/${event.target.textContent}.pdf`;
  });
});
  • id should be unique. try with same class – sauhardnc May 07 '20 at 17:59
  • Does this answer your question? [JavaScript and getElementById for multiple elements with the same ID](https://stackoverflow.com/questions/3607291/javascript-and-getelementbyid-for-multiple-elements-with-the-same-id) – Heretic Monkey May 07 '20 at 18:01

3 Answers3

3

you shouldn't use same id element, it would work here but it's frowned upon. I've created a demo with the same class. Of course, the iframe wouldn't load. I've done the explaining in the code itself. See, if it works for you.

const selectedActivity = document.querySelectorAll(".other-activies-link");

selectedActivity.forEach((link) => {
  link.addEventListener("click", (event) => { // pass event parameter here
  
    document.getElementById(
      "myFrame"
    ).src = `/files/${event.target.innerText}.pdf`; // use innerText instead
    console.clear();
    console.log(event.target.innerText);
    console.log(event.target.textContent);
  });
});
<p><a class="other-activies-link">Semana<br> Omnistack 11</a></p>
<p><a class="other-activies-link">28ª Semana do IME</a></p>

<div id="myModal" class="modal">
 <div class="modal-content">
  <span class="close">&times;</span>
  <iframe id="myFrame" frameborder="0" allowfullscreen></iframe>
 </div>
</div>

See the difference between innerText and textContent here.

sauhardnc
  • 1,961
  • 2
  • 6
  • 16
2

You shouldn't use non-unique ids. If you replace id with a class, the code should work.

V1raNi
  • 313
  • 1
  • 11
1

You should use classes instead, id's of elements should always be unique

<p><a class="other-activies-link">Semana Omnistack 11</a></p>
<p><a class="other-activies-link">28ª Semana do IME</a></p>

<div id="myModal" class="modal">
 <div class="modal-content">
  <span class="close">&times;</span>
  <iframe id="myFrame" frameborder="0" allowfullscreen></iframe>
 </div>
</div>

This should work,

const selectedActivity = document.querySelectorAll(".other-activies-link");

...
dqve
  • 646
  • 6
  • 18