0
document.querySelectorAll("table[id^='Table']");

This code selects all tables with the id of Table. But i want to select tables with id of Table2 OR Table7 (or any other numbers). How to do this with regex?

Edit: jQuery is not applicable in my case.

9
  • jquery is not applicable in my case Commented Mar 14, 2013 at 13:57
  • 1
    The code in the question should do this. Why don't you use that? Commented Mar 14, 2013 at 13:58
  • I want also add a number match and have no idea to do this with regex Commented Mar 14, 2013 at 13:58
  • Its working for me jsfiddle.net/qQ7VT Commented Mar 14, 2013 at 13:59
  • Ah, so Tablesomeletters should not match, but table6 (or any other number) should? @Adige72 Commented Mar 14, 2013 at 13:59

1 Answer 1

2
function getTables(tableNumbers) { // Usage: getTables([2, 7]) will return the tables with the ID 'Table2' and 'Table7'. (You can add more numbers; [2,7,3,6])
    var allTables = document.querySelectorAll("table[id^='Table']");
    var tablesWeWant = [];
    for (var i = 0; i < allTables.length; i++) {
        if (allTables[i].id.match(/Table[0-9]/)) {
            tablesWeWant.push(allTables[i]);
        }
    }
    for (var i = 0; i < tablesWeWant.length; i++) {
        if (!tableNumbers.contains(tablesWeWant[i].id.substr(id.length - 1))) {
            tableNumbers.splice(i, 1);
        }
    }
    return tablesWeWant;
}

This should return all tables with an ID matching the regex /Table[0-9]/ and ending with a digit contained in the variable tableNumbders.

DISCLAIMER: I'm not a regex expert.

EDIT:
After editing a few times the code above became a bit too long, so I rewrote it like this:

function getTables(tableNumbers) {
    var tablesWeWant = [];
    for (var i = 0; i < tableNumbers.length; i++) {
        tablesWeWant.push(document.querySelector("#Table" + tableNumbers[i]));
    }
    return tablesWeWant;
}

The second approach works: http://jsfiddle.net/qQ7VT/1/

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

6 Comments

I just adjusted the regex. (I removed the + to match only one digit.) @Adige72
There's a problem. Even tablesWeWant is empty it selects all Table*
I don't understand your last comment. If tablesWeWant is empty, it didn't select any tables at all! Let me make an edit to make the code more clear. @Adige72
I've tried var tablesWeWant = [2, 7]; to select tables with id of Table2 and Table7 but it selects all tables
Ah! No, that's not how the code is meant to work. The code will select all tables with an ID that match that regex, and put them in the variable tablesWeWant. I will make another edit. @Adige72
|

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.