views:

183

answers:

2

Hello,

I have a div element in HTML document.

I would like to extract all elements inside this div which id starts with a known text (e.g. "q17_").

How can I achieve this using JavaScript ?

(If needed, for simplicity, I can assume that all elements inside the div are of type input or select.)

Thanks !

+1  A: 
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
    if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
        if(searchEles[i].id.indexOf('q1_') == 0) {
            matches.push(searchEles[i]);
        }
    }
}

Once again, I strongly suggest jQuery for such tasks:

$("#myDiv :input").hide(); // :input matches all input elements, including selects
karim79
I would probably go with jQuery in future, but now I need to do this with JavaScript.The problem with your code is that "children" are only the sons of myDiv. In my case, inputs and selects can be deep inside the div rather that immediate sons.
Misha Moroshko
@misha-moroshko - now that we're talking *recursion* I *stronglier* suggest using jQuery, as above. :)
karim79
:) So what you say is that I must write a recursive function if I want to do this in JavaScript ? No alternatives in JavaScript ??
Misha Moroshko
If you know what the markup looks like, there isn't a need for recursion - as code specific to your DOM can be written to extract what is needed. I would suggest that you post it, for a better response.
karim79
A: 
// Option 1: Likely fastest but not supported by early Firefoxes
var elements = document.getElementById('parentContainer').children;

// Option 2: Likely slowest
var elements = document.getElementById('parentContainer').getElementsByTagName('*');

// Option 3: Requires change to code (wrap a form instead of a div around it)
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;

var matches = [];

for (var i = 0; i < elements.length; i++)
    if (elements[i].value.indexOf('q17_') == 0)
        matches.push(elements[i]);
Casey Hope
Again, I need to collect all elements deep inside the tree, not only the sons.
Misha Moroshko