Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
JS alter element with certain id and class name

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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"
about 4 years ago · Juan Pablo Isaza Report

0

is the code pasted is right from the source code.

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

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!