Home > Software engineering >  JS alter element with certain id and class name
JS alter element with certain id and class name

Time:07-04

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" >Test...</div>
<div id="2" >Test...</div>
<div id="3" >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?

CodePudding user response:

is the code pasted is right from the source code.

The above function showTabContent() should accept argument. showTabContent(tabId)

CodePudding user response:

You have to pass tabID as argument in function, also don't need classList.contains()

function showTabContent(tabID) {
  document.getElementById(tabID).style.display = "block";
}

showTabContent(2);
div {
 display: none
}
<div id="1" >Test...</div>
<div id="2" >Test...</div>
<div id="3" >Test...</div>

CodePudding user response:

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" >Test...</div>
<div id="2" >Test...</div>
<div id="3" >Test...</div>

CodePudding user response:

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"
  • Related