开发者

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?


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


If you mean the id attribute you can do...

var elems = document.getElementsByTagName('*');

var myElems = [];

for(var i = 0, length = elems.length; i < length; i++) {

   if (elems[i].id.match(/^work_/)) {
    myElems.push(elems[i]);
   }

}

myElems will contain all elements where their id attribute starts with work_.

See it on jsfiddle.net

If you mean the class attribute it is a little different.

var elems = document.getElementsByTagName('*');

var myElems = [];

for(var i = 0, length = elems.length; i < length; i++) {

   var classes = elems[i].className.split(' '); 

   for (var j = 0, classesLength = classes.length; j < classesLength; j++) {    
       // If you have a trim function, use it on the class name.
       if (classes[j].match(/^work_/)) {
           myElems.push(elems[i]);
           break;
       }
   }

}

See it on jsfiddle.net

Of course if you use a library such as jQuery it is much easier.

$('*[id^=work')


You can use the same class for all such elements and select them by class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜