Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using document.getElementById with partial ID name

Tags:

javascript

css

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...

like image 325
Gerard Avatar asked Aug 24 '13 18:08

Gerard


2 Answers

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.

like image 196
ComFreek Avatar answered Oct 03 '22 21:10

ComFreek


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.

like image 37
Niet the Dark Absol Avatar answered Oct 03 '22 22:10

Niet the Dark Absol