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
.
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.
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.
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.
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.
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
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With