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
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">
 // Find all images that contain a name attribute which starts with "pro", use *= if the name contains "pro"

  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);
Answered about 7 years ago by Mottie
  • This worked like a charm, thank you! Imhotep about 7 years ago
o.k.w 2355

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

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 about 7 years ago by o.k.w
danwellman 5600

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 about 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 about 7 years ago
  • I think you want to do getElementsByTagName('img') instead of getElementsByName. Gary Hepting about 7 years ago