I am following a tutorial on making tabs in html/js. The approach here is that we have a ul of buttons that target other elements in the html.
<ul class="tabs">
<li data-tab-target="#overview">
<button class="tab-button" id='tab-button-1'>
Overview
</button>
</li>
<li data-tab-target="#learn">
<button class="tab-button" id='tab-button-2'>
Learn
</button>
</li>
<li data-tab-target="#more">
<button class="tab-button" id='tab-button-3'>
More
</button>
</li>
</ul>
These li's all have data attributes that correspond to these divs:
<div id="#overview" data-tab-content>
This is a test.
</div>
<div id="#learn" data-tab-content>
Learn blah blah blah
</div>
<div id="#more" data-tab-content>
Something something something.
</div>
The point here is that when we click on a button in the ul, JavaScript finds the target that button corresponds to and adds a class that we can style with css (make it not hidden etc.)
The JS of the tutorial has the following code, which is supposed to add class 'active' to the data-target of the tab when it is clicked:
const tabs = document.querySelectorAll('[data-tab-target]');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const target = document.querySelector(tab.dataset.tabTarget);
target.classList.add('active');
})
})
The first line const tabs = document.querySelectorAll('[data-tab-target]');
returns the elements of the ul but when I click on one of the tabs, the console gives me the error: Cannot read property 'classList' of null.
To try and see what was wrong, I did console.log(tab.dataset.tabTarget)
and it gave me the data target of the first element in the ul, #overview. I have no idea what is wrong, for some reason it assigns target to be a null value. The code obviously applies to each tab because it gives me the same error when I click on any of them. Help is appreciated :) I will link the video if more context is needed: https://www.youtube.com/watch?v=5L6h_MrNvsk.
question from:
https://stackoverflow.com/questions/66057310/query-selector-returns-a-null-value-for-data-target-but-console-log-shows-that 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…