Using document.getElementById with a partial identification name

I 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 the div after 2.5 seconds. It works fine, but the problem is that the div I want to adjust is dynamic. Only the first word is always the same (gatewayContainerstacks). After that, the identifier is dynamic (part of _in_9_page4). Is there a way to do a code search from a div starting with gatewayContainerstacks? I would appreciate a tip .. Thanks ...

+4
source share
2 answers

Use document.querySelector () :

 function showIt() { document.querySelector('[id^="gatewayContainerstacks"]').style.visibility = "hidden"; } setTimeout("showIt()", 2500); // after 2.5 sec 

By the way, please do not put showIt() in quotation marks; better refer to this function:

 setTimeout(showIt, 2500); 
+5
source

Well, firstly, you should NEVER pass a string to setTimeout . In this case, you can just pass showIt (without parentheses!), And it will work fine.

As for your real 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 prior to version 8 and may not work in some older mobile browsers.

For a more general solution, I suggest providing a unique and well-known identifier, and then putting other information in the data-* attributes:

 <div id="gatewayContainerstacks" data-in="9" data-page="4">...</div> 

Or something like that.

+2
source

Source: https://habr.com/ru/post/1498752/


All Articles