Hope you can help me with this problem... My code:
function showIt() {
document.getElementById("gatewayContainerstacks_in_9_page4").style.visibility = "hidden";
}
setTimeout("showIt()", 2500); // after 2.5 sec
I want to hide a div after 2.5 sec. It is working fine but the problem is that the div I want to target is dynamic. Only the first word is always the same (gatewayContainerstacks). After that the ID is dynamic (the _in_9_page4 part). Is there a way to make the code search out the div starting with gatewayContainerstacks? I would appreciate a hint.. Thanks...
Use document.querySelector() in conjunction with the CSS attribute selector ^=
to match elements with IDs starting with the desired prefix:
function showIt() {
document.querySelector('[id^="gatewayContainerstacks"]').style.visibility = "hidden";
}
setTimeout(showIt, 2500);
Here, I also passed the function showIt
as such (and not as a string) to setTimeout
. See MDN on setTimeout
for the reasons.
Well, first off, you should NEVER pass a string to setTimeout
. In this case, you can just pass showIt
(no parentheses!) and it'll work just fine.
As for your actual problem, you can try something like this:
document.querySelector("[id^=gatewayContainerstacks]").style.visibility = "hidden";
However keep in mind that this will not work in Internet Explorer before version 8, and may not work in some older mobile browsers either.
For a more general solution, I'd suggest giving a unique and known ID, and then putting other information into data-*
attributes:
<div id="gatewayContainerstacks" data-in="9" data-page="4">...</div>
Or something like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With