I have an HTML page. I would like to extract all elements whose name starts with "q1_".
How can I achieve this in JavaScript?
JavaScript String startsWith()The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive. See also the endsWith() method.
The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.
A quick and easy way is to use jQuery and do this:
var $eles = $(":input[name^='q1_']").css("color","yellow");
That will grab all elements whose name attribute starts with 'q1_'. To convert the resulting collection of jQuery objects to a DOM collection, do this:
var DOMeles = $eles.get();
see http://api.jquery.com/attribute-starts-with-selector/
In pure DOM, you could use getElementsByTagName
to grab all input elements, and loop through the resulting array. Elements with name
starting with 'q1_' get pushed to another array:
var eles = []; var inputs = document.getElementsByTagName("input"); for(var i = 0; i < inputs.length; i++) { if(inputs[i].name.indexOf('q1_') == 0) { eles.push(inputs[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