26

I have a div element in an HTML document.

I would like to extract all elements inside this div with id attributes starting with a known string (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.

twernt
  • 20,271
  • 5
  • 32
  • 41
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

6 Answers6

37
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
  • 339,989
  • 67
  • 413
  • 406
  • 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 Apr 11 '10 at 16:51
  • 1
    @misha-moroshko - now that we're talking *recursion* I *stronglier* suggest using jQuery, as above. :) – karim79 Apr 11 '10 at 16:56
  • :) 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 Apr 11 '10 at 17:00
  • 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 Apr 11 '10 at 18:08
  • Can you please explain the jQuery a bit more. I am also looking for put all elements in an array. – basickarl Mar 07 '13 at 14:38
  • Hi folks, for anyone stumbling across this answer in 2022, please see my alternative answer. No need for either jQuery or JavaScript loops these days. – Josh Gallagher Apr 21 '22 at 10:15
17

Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :

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]);
Community
  • 1
  • 1
Casey Chu
  • 25,069
  • 10
  • 40
  • 59
6

With modern browsers, this is easy without jQuery:

document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');

The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".

Note that all browsers released since June 2009 support this.

Josh Gallagher
  • 5,211
  • 2
  • 33
  • 60
2

Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:

function fillArray(vector1,vector2){
    for (var i = 0; i < vector1.length; i++){
        if (vector1[i].id.indexOf('q17_') == 0)
            vector2.push(vector1[i]);
        if(vector1[i].tagName == 'DIV')
            fillArray (document.getElementById(vector1[i].id).children,vector2);
    }
}

function selectAllElementsInsideDiv(divId){ 
    var matches = new Array();
    var searchEles = document.getElementById(divId).children;
    fillArray(searchEles,matches);
    return matches;
}

Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:

var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv =  selectAllElementsInsideDiv('myDiv')

I have tested it and it worked for me. I hope it helps you.

Nicholas Murray
  • 13,305
  • 14
  • 65
  • 84
2
var $list = $('#divname input[id^="q17_"]');   // get all input controls with id q17_

// once you have $list you can do whatever you want

var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {

    var id = $(this).prop("id");      // get id
    var cbx = '';
    if ($(this).is(':checkbox') || $(this).is(':radio')) {
        // Need to see if this control is checked
    }
    else { 
        // Nope, not a checked control - so do something else
    }

});
2

i have tested a sample and i would like to share this sample and i am sure it's quite help full. I have done all thing in body, first creating an structure there on click of button you will call a function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens. I have given alerts here on different level so u can test where r u now in the coding .

    <body>
    <h1>javascript to count the number of children of given child</h1>

    <div id="count">
    <span>a</span>
    <span>s</span>
    <span>d</span>
    <span>ff</span>
    <div>fsds</div>
    <p>fffff</p>
    </div>
   <button type="button" onclick="selectallelement('count')">click</button>
   <p>total element no.</p>
    <p id="sho">here</p>
  <script>

  function selectallelement(divid)
  {
 alert(divid);
 var ele = document.getElementById(divid).children;
 var match = new Array();
  var i = fillArray(ele,match);
  alert(i);
   document.getElementById('sho').innerHTML = i;
  }
 function fillArray(e1,a1)
  {
 alert("we are here");
   for(var i =0;i<e1.length;i++)
{
  if(e1[i].id.indexOf('count') == 0)
    a1.push(e1[i]);
}
return i;
   }
   </script>

 </body>

  USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS 
aabhi
  • 47
  • 9