karthick karthick - 5 months ago 8
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

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" />
<script>
    $('input[name^="work_"]').val('work here!');
</script>

http://api.jquery.com/attribute-starts-with-selector/

http://api.jquery.com/category/selectors/

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...
     }
}
Comments