0

I have a simple function that checks selected div ids, and performs an action if a particular div is present:

function checkContent_m(){
var mItems = [document.getElementById('m_round1'),document.getElementById('m_round2'),document.getElementById('m_round3'),document.getElementById('m_round4'),
document.getElementById('m_round5'),document.getElementById('m_round6'),document.getElementById('m_round7'),document.getElementById('m_round8')];

if (mItems.length > 0){
        document.getElementById('m_div').style.display = "block";       
}
else{
    document.getElementById('m_div').style.display = "none";
}

}

Seems to me that there might be a way for me to construct my array more efficiently. How would I construct a regular expression that would be an equivalent to:

document.getElementById('m_round'+ '*')

Such statement would allow me to add an unlimited number of "m_round" divs, without having to modify my js function.

4
  • The traditional wisdom here is to apply a common class to all the elements you want and then select them with document.getElementsByClassName("myClass"). Commented Nov 9, 2012 at 19:23
  • 2
    That would only work in browsers that support HTML5. Commented Nov 9, 2012 at 19:25
  • Why do you test mItems.length > 0? It is always true. Commented Nov 9, 2012 at 19:31
  • do not use ids for that, a better practice would be to use data-* attributes.. Commented Nov 9, 2012 at 19:33

1 Answer 1

3

Consider using jQuery. Then selecting ID's that have similar names is trivial...

$('[id^="m_round"]')

Of course, you could also give all the elements you want to select the same class and then select them that way...

$('.m_round')
Sign up to request clarification or add additional context in comments.

3 Comments

and that syntax would be something like "var = $('[id^="m_round"]');" ?
Yep, that will get you a jQuery object that represents all elements with and ID that contains m_round. @kjarsenal
just tested this. works like a fricken charm! I'm grateful, thank you.

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.