Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all elements inside "div" that starts with a known text

Tags:

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.

like image 488
Misha Moroshko Avatar asked Apr 11 '10 16:04

Misha Moroshko


People also ask

How do I get all the elements inside a div?

You can use the children property of getElementById() method in JavaScript to get or extract unique ids of all the DIV elements inside a DIV element.

How do I get text inside a div?

Use the textContent property to get the text of a div element, e.g. const result = element. textContent . The textContent property will return the text content of the div and its descendants. If the element is empty, an empty string is returned.

How do I get all elements of a specific ID?

Use the document. querySelectorAll() method to get all elements whose id starts with a specific string, e.g. document. querySelectorAll('[id^="box"]') . The method returns a NodeList containing all the elements that match the provided selector.

How do you get an element inside a tag?

You access an element by tag with the getElementsByTagName() method. For our tag example, we're using article elements. Just like accessing an element by its class, getElementsByTagName() will return an array-like object of elements, and you can modify every tag in the document with a for loop.


2 Answers

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 
like image 73
karim79 Avatar answered Sep 22 '22 21:09

karim79


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]); 
like image 43
Casey Chu Avatar answered Sep 22 '22 21:09

Casey Chu