I'm trying to hide elements by their ids:
document.getElementById('Table1').style.display = 'none';
But there are many divs goes like Table1, Table2, Table3...
So how to use regular expressions in a situation like this?
Set class to all these elements. It was invented for such cases.
HTML:
<div id="Table1" class="myTables"></div>
<div id="Table2" class="myTables"></div>
<div id="Table3" class="myTables"></div>
JavaScript:
var elements = document.getElementsByClassName("myTables");
for (var i = 0, len = elements.length; i < len; i++) {
elements[i].style.display = "none";
}
UPDATE: If setting classes is not applicable in your case, you can always use the modern method querySelectorAll with attribute starts with selector:
var elements = document.querySelectorAll("div[id^='Table']");
for (var i = 0, len = elements.length; i < len; i++) {
elements[i].style.display = "none";
}
Regural expression will not work in this example.
Either use a common class name on all the elements, or, if you cannot change HTML, you can use Selectors API to select the elements you need to hide.
Use
var allElemsWithIdStartingFromTable = document.querySelectorAll('[id^="Table"]');
to select all elements with ID starting with "Table", so it would be Table1, Table2, but also TableOfProducts, keep that in mind.
Then you need to iterate over this and check if the id attribute matches /^Table\d+$/ regular expression.
for example..if you give myTables as class name for div..use that for lenght..
var elements = document.getElementsByClassName("myTables");//to know the length only..
for(var i=0;i<elements.length;i++)
{
document.getElementById('Table'+i).style.display = 'none';
}
use looping concept..its an example..
Table*. I think it requires regex, doesnt it?