I currently make a tab which the tab content is containing iframe. I want it to every time the tab is clicked, the iframe reload the page.
But when I inspected, the source attributes exist in every iframe, and the issues shows up that states: Uncaught TypeError: Cannot read properties of undefined (reading 'setAttribute'). I'm very new in JavaScript, and have no idea to code. Please help me through this. Thank you so much.
So, here's the code :
let tabs = document.querySelectorAll('.tab');
let content = document.querySelectorAll('.content-item');
for (let i = 0; i < tabs.length; i++) {
tabs[i].addEventListener('click', () => tabClick(i));
}
function tabClick(currentTab) {
removeActive();
tabs[currentTab].classList.add('active');
content[currentTab].classList.add('active');
content[currentTab].removeAttribute('src');
}
function removeActive() {
for (let i = 0; i < tabs.length; i++) {
tabs[i].classList.remove('active');
content[i].classList.remove('active');
content[i].setAttribute('src', content[i].getAttribute('data-src'));
}
}
.container {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.tabs {
display: flex;
justify-content: center;
width: 100%;
}
.tab {
font-size: 16px;
padding: 5px 15px;
cursor: pointer;
}
.tab.active {
background-color: rgb(250, 97, 9);
}
.content {
width: 100vw;
margin-top: 50px;
}
.content-item {
display: none;
padding: 0px;
border: none;
}
.content-item.active {
display: flex;
justify-content: center;
}
.content-iframe {
border: none;
padding: 0px;
margin: 0px;
width: 100vw;
height: 50vh;
}
<div class="container">
<div class="tabs">
<div class="tab active">Tokyo</div>
<div class="tab">Paris</div>
<div class="tab">Washington</div>
<div class="tab">Jakarta</div>
<div class="tab">London</div>
</div>
<div class="content">
<div class="content-item active">
<iframe class="content-iframe" data-src="https://en.wikipedia.org/wiki/Tokyo" src="https://en.wikipedia.org/wiki/Tokyo" loading="lazy"></iframe>
</div>
<div class="content-item">
<iframe class="content-iframe" data-src="https://en.wikipedia.org/wiki/Paris" src="https://en.wikipedia.org/wiki/Paris" loading="lazy"></iframe>
</div>
<div class="content-item">
<iframe class="content-iframe" data-src="https://en.wikipedia.org/wiki/Washington" src="https://en.wikipedia.org/wiki/Washington" loading="lazy"></iframe>
</div>
<div class="content-item">
<iframe class="content-iframe" data-src="https://en.wikipedia.org/wiki/Jakarta" src="https://en.wikipedia.org/wiki/Jakarta" loading="lazy"></iframe>
</div>
<div class="content-item">
<iframe class="content-iframe" data-src="https://en.wikipedia.org/wiki/London" src="https://en.wikipedia.org/wiki/London" loading="lazy"></iframe>
</div>
</div>
</div>