I need to access multiple divs at once. I cannot use ids and I was wondering if there was a way in javascript to access something like htmls class? Instead of: document.getElementById() I need something like document.getElementByClass() Is there any way I can do this? Thanks.
For example you can do like this: all_divs = document.getElementsByTagName("div"); if(all_divs.length>0){ var num = 0; for(var i=0; i<all_divs.length; i++){ the_class = all_divs[i].className; pattern = /(\s|^)yourclassname(\s|$)/; if(!pattern.test(the_class)){ continue; } the_divs[num] = all_divs[i]; num++; } } Code (markup): All divs, which class is yourclassname, are in the array the_divs.
you can also use the power of jquery selectors. The each() function iterates over each div that matches the selector: $('div.yourclassname').each(function(){ //do some stuff to your div here }); Code (markup):
Nice function! It isn't working for me though: all_divs = document.getElementsByTagName('div'); if(all_divs.length>0){ var num = 0; for(var i=0; i<all_divs.length; i++){ the_class = all_divs[i].className; pattern = /(\s|^)[COLOR="red"]main[/COLOR](\s|$)/; if(!pattern.test(the_class)){ continue; } [COLOR="red"]document.getElementByTagName(all_divs[i]).style.display = '';[/COLOR] //the_divs[num] = all_divs[i]; num++; } } Code (markup): It's supposed to show the divs who have 'main' as their class. But it isn't finding them? I checked and it did loop through all the divs but it isn't finding the one I want. Why is this? Thanks.
i've worked it out this way - a test example can be seen here: demetri-media.com/JavaScript/AllDivtags.html clicking the button does a function to change the background of all divs with a class of 'dev' to be red. this is the code i wrote to do that. actually , quite simple.... function change(){ all_divs = document.getElementsByTagName("div"); for (var i=0;i<all_divs.length;i++){ if (document.getElementsByTagName('div')[i].className =='[COLOR="Red"]dev[/COLOR]') {document.getElementsByTagName('div')[i].[COLOR="Red"]style.backgroundColor='red'[/COLOR];} } } Code (markup): just change the div calss name, and change the function ( evrything that's in red...) to be what you need.hope that helps!
Imozeb try this example all_divs = document.getElementsByTagName('div'); if(all_divs.length>0){ for(var i=0; i<all_divs.length; i++){ the_class = all_divs[i].className; pattern = /(\s|^)main(\s|$)/; if(!pattern.test(the_class)){ continue; } all_divs[i].style.display = ''; } } Code (markup):