Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all elements which name starts with some string?

I have an HTML page. I would like to extract all elements whose name starts with "q1_".

How can I achieve this in JavaScript?

like image 293
Misha Moroshko Avatar asked Apr 11 '10 15:04

Misha Moroshko


People also ask

How to match starting string 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.

What is startsWith in JavaScript?

The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

How do I add multiple ids to Queryselector?

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.


1 Answers

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]);     } } 
like image 196
karim79 Avatar answered Oct 04 '22 03:10

karim79