Solution 1 :

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.

Solution 2 :

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

Solution 3 :

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");

...

Problem :

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

Comments

Comment posted by sauhardnc

id should be unique. try with same class

Comment posted by JavaScript and getElementById for multiple elements with the same ID

Does this answer your question?

Comment posted by Murilo de Jesus

I replaced the ids with classes and the textcontent with innnertext and the modals didn’t open anymore

Comment posted by Murilo de Jesus

But replacing just the ids with classes worked perfectly. Thanks

By

Leave a Reply

Your email address will not be published. Required fields are marked *