karthick karthick - 2 years ago 59
Javascript Question

How to select a list of elements by name?

i want to select all the elements that start with a particular sequence.
The sequence will be like work_XXXXXX. how to achieve this?

Answer Source

I am providing answers in both jquery and javascript but best option is use jquery because with javascript you will have to loop throught all elements and match your desired patteren which is very time consuming process so my preference is use jquery:

finds all inputs with an attribute name that starts with 'work_' and puts text in them.

<input name="newsletter" />

<input name="work_man" />
<input name="work_boy" />
    $('input[name^="work_"]').val('work here!');



with javascript their is no builtin keyword for this, but you can do it by loop through all elements and check for match of your desired pattern, this way:

var idStart = "work_";
var componentContainer = document.getElementById("containerTable").getElementsByTagName("DIV");
for (var i = 0; i < componentContainer.length; i++) {
     var id = componentContainer[i].id;
     if ((id.length >= idStart.length) && (id.substring(0, idStart.length - 1) == idStart))// you can also use regular expression here to match desired pattern
          //do something...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download