1

I just want to know to how to use custom varible with javascript.suppose we have 5 id with name zawsz,baws2,tawsx,paws4,vawsa and we want to execute single DOM command to all these element whose id is define here.

document.getElementById("-aws-").onclick=function(){}  

Here -aws- define all the id define above.(-) can be replace with any char/int value;

sanjeet pal
  • 139
  • 2
  • 11
  • 2
    Does this answer your question? [Javascript getElementById based on a partial string](https://stackoverflow.com/questions/6991494/javascript-getelementbyid-based-on-a-partial-string) – johannchopin Feb 16 '20 at 18:49

2 Answers2

1

You can use document.querySelectorAll for this:

document.querySelectorAll('[id^="aws"]')

That will select all elements where the id attribute starts with (^=) "aws".

mrbnsn
  • 11
  • 4
1

You could use the following code: (The following code will select all elements of which the id includes aws. I have tested this code and it works: https://jsfiddle.net/5042woqz/)

document.querySelectorAll('*[id*="aws"]').forEach(function(item) {
    item.onclick=function() {
        console.log('click!');
    };
});

Items will now be an array containing all your aws- items. If you have further questions, just let me know.

P.S.: You could achieve the same thing really easily with jquery.