Reputation: 1124
I'm trying to change the style of a div with vanilla JS. The div should have a certain id and the class name tab-content
:
function showTabContent() {
document.getElementById(tabID).classList.contains("tab-content").style.display = "block";
}
HTML:
<div id="1" class="tab-content">Test...</div>
<div id="2" class="tab-content">Test...</div>
<div id="3" class="tab-content">Test...</div>
If for example I run:
showTabContent(2);
It should set the tab-content
div with id 2
to style display block. It is not working. What am I doing wrong?
Upvotes: 1
Views: 69
Reputation: 609
First of all you should pass tabID to your function.
.containe() method in JavaScript shows whether a string has a specific word or letter and if the condition is true, it will return true
. (boolean)
if you want to get the element with a specific ID and tab-content
class, you can work with querySelector
.
document.querySelector("#"+tabID+".tab-content").style.display="block"
But since ID is most often unique, referring to the ID alone is sufficient.
document.getElementById(tabID).style.display="block"
Upvotes: 1
Reputation: 25408
Since you are passing the id
to function showTabContent
then you can receive it using parameter i.e tabId
.
then you have to find the element and check for its existence. It could be possible that the element with specified id
is not present.
function showTabContent(tabId) {
const element = document.getElementById(tabId);
if (element) {
element.style.display = "block";
element.style.backgroundColor = "lime"; // FOR VISUAL PURPOSE ONLY
}
}
showTabContent(2);
<div id="1" class="tab-content">Test...</div>
<div id="2" class="tab-content">Test...</div>
<div id="3" class="tab-content">Test...</div>
Upvotes: 0
Reputation: 16
is the code pasted is right from the source code.
The above function showTabContent()
should accept argument.
showTabContent(tabId)
Upvotes: 0