Before today I have never before used JavaScript so I’m trying to learn as I go here.
On a webpage I want to select all html input tags with the class “exampleClass” and I want to replace the value. Can anyone show me a good/quick code snippet on how to do this or point me in the right direction to another thread or tutorial?
Thank you!
Plain Javascript
In plain javascript (no jQuery-like framework), you could do it like this:
But,
getElementsByClassName()isn’t supported in older versions of IE (not until IE9). If you want to make the plain JS version work with older browsers, then you have to get a substitute forgetElementsByClassName()for use when it isn’t supported. There are many implementations which you can find with Google. Here’s one of them: http://robertnyman.com/2008/05/27/the-ultimate-getelementsbyclassname-anno-2008/.jQuery
Frameworks like jQuery are very, very useful for this kind of operation and they have better cross-browser and old-browser support. In jQuery, this operation would work pretty much everywhere and be just this one line.
Sizzle
If you want good cross-browser support, but want something lighter weight than jQuery, you can use just the Sizzle selector library (which is what is used inside of jQuery) in which case the code would be this: