I have a button called WatchMode.
When you click this button, it will close certain divs, specified by the div ID.
The javascript for this is as follows:
function watchmode() {
document.getElementById('aps30').innerHTML = " ";
}
Now, I want to do the same for a div that appears twice on my page, this div has a Class instead of an ID.
I tried adding this line to the javascript, but it doesn't seem to work
document.getElementByClassName('floater').innerHTML = " ";
Any suggestions ??
Your function name has a spelling mistake — it should be
getElementsByClassName
(note the plural, elements, not element):The easiest way to do this is to use jQuery. Here is a post that should answer your question:
How to getElementByClass instead of GetElementById with Javascript?
You have to change a number of things:
Here's the code:
This is a place where jQuery is really useful. In jQuery, it would just be:
That would automatically find all objects with that class and set the innerHTML of all matching objects to your string.
First, I am not sure whether this was a typo or not, but you put:
The command is actually:
notice elements is plural.
Now, this doesn't behave the same as getElementById. It returns a nodelist, or in other words a list of all the elements with the specified class.
You can store the results in an array like so:
and then loop through the results to perform your actions:
I have not tested the code that I wrote out here, but the method is tried and true.
[edit] I forgot to mention that this function is not supported by IE, and you can accomplish this using jQuery by doing something like: $('floater').html('text'); and it is cross-browser. You can also search the web for something that emulates the behavior of getElementsByClassName and works in all browsers.
Here is an article with a better function that emulates getElementsByClassName:
http://www.webmuse.co.uk/blog/custom-getelementsbyclassname-function-for-all-browsers/
This works very well, is cross browser compatible, and is used the same way as getElementsByClassName.
usage example from the article: var el = document.getElementsByClassName("para");