0

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?

2
  • Regular expressions aren't useful here. Do you want to use them for any particular reason? Commented Mar 11, 2013 at 11:47
  • My reason is to hide all elements with the id Table*. I think it requires regex, doesnt it? Commented Mar 11, 2013 at 11:59

3 Answers 3

2

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";
}

DEMO: http://jsfiddle.net/L2de8/

Sign up to request clarification or add additional context in comments.

1 Comment

For specific reasons, it's not applicable to assign classes in my project.
1

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.

Comments

0

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

1 Comment

@VisioN your way is good..i like your answer..for length purpose there is no other way..i felt your is better way..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.