简体   繁体   中英

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?

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"

is the code pasted is right from the source code.

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

Since you are passing the id to function showTabContent then you can receive it using parameter ie 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM