I have some img elements where the name attributes all start with a specific prefix (i.e. name="proGamer" / name="proReader" etc).

Is there something like document.getElementsByName(regexp) ?

I want to iterate on them adding a specific attribute for all of them.

3 answers

Mottie 1134
2
points
This was chosen as the best answer

I would suggest using jQuery for something like this, it'll make your life much easier.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 // Find all images that contain a name attribute which starts with "pro", use *= if the name contains "pro"
 $('img[name^="pro"]').each(function(){

  var proname = $(this).attr('name'); // contains the name "proReader" or "proGamer", etc
  var newAttrValue = '';

  if (proname == "proGamer") newAttrValue = 'This is a Gamer';
  if (proname == "proReader") newAttrValue = 'This is a Reader';
  // etc, or you can use switch/case

  // add the attribute
  $(this).attr('someattribute', newAttrValue);
 })
})
</script>
Answered almost 7 years ago by Mottie
  • This worked like a charm, thank you! Imhotep almost 7 years ago
o.k.w 2355
2
points

I think Fudgey's solution using jQuery is ideal.

You also give this jQuery plugin a try:
Regex Selector for jQuery

For your case, it'll be:

$(':regex(name,^prefix)').each(function() {
   //...other codes...
   this.attr('attributeName','attributValue'); 
  });

If using just vanilla javascript, you will have to iterate EVERY DOM item from the document root and check their names against the prefix.

Answered almost 7 years ago by o.k.w
danwellman 5600
0
points

in plain-vanilla JS you want something like:

var els = document.getElementsByName("the_name");

Els would then be a collection of matching elements that you could iterate over with a simple for loop:

for (var x - 0; x < els.length; x++){
  els[x].className = "something"
}

className is just an example of something you could update within the loop...

Answered almost 7 years ago by danwellman
  • It seems I didn't make my self clear enough. The img elements already have a name which I don't want to change. The all have a different name which has the same prefix "pro". So I can't use the document.getElementsByName() method, since the name is not common, just part of it. The reason I want sth like that is because I want to iterate on them. Imhotep almost 7 years ago
  • I think you want to do getElementsByTagName('img') instead of getElementsByName. Gary Hepting almost 7 years ago