# Solved: Loop through all elements of a webpage



## -Fabez- (Jul 28, 2008)

Is there a way to loop through all elements in a web page, querying & possibly changing some properties such as CSS ? So far all I have found is Document.GetElementByID, etc but nothing to loop through every possible element on the page. 

Also is it possible to use code to shift or change colours defined by CSS on a webpage, so as every time the colour green is used it can be mass changed to another colour for example ?

Thanks -Fabez-


----------



## andythepandy (Jul 2, 2006)

Are the elements you want to loop through all of one kind, like are they all divs or all inputs etc?

Andy


----------



## simonb89 (Jun 18, 2010)

This javascript should help, if it doesn't then try looking at the php foreach loop.

var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++){ 
var divname = divs_.id; 
if(divname.indexOf("text") == 0) {

}
}_


----------



## -Fabez- (Jul 28, 2008)

Thank you for the replies. Andythepandy, I would like to loop through every element type that can have positioning and style properties added to it. Simonb89, that code looks like it should work, however when I put it into a simple web page with an alert in the loop, it doesn't seem to work, any idea's ? Thanks, -Fabez-


----------



## andythepandy (Jul 2, 2006)

Fabez, you are going to need what simonb89 suggested, but instead of specifing a tag name, use an asterisk *.


```
var x = document.getElementsByTagName('*');
for(var i = 0; i < x.length; i++)
{
    x[i].style.backgroundColor = 'red';
    //You can do whatever you want inhere. x[i] represents the current tag and the loop will loop through all elements in the page
}
```
The asterisk means find all tags regardless of their name.
Hope that does it 

Andy


----------



## andythepandy (Jul 2, 2006)

And another thought. As the loop will go through every tag in the html, including the head tag, any script or style tags etc.

You may want to add a check in the loop like

```
for(var i = 0; i < x.length; i++)
{
if(x[i].tagName == "HTML" || x[i].tagName == "HEAD" || x[i].tagName == "SCRIPT" || x[i].tagName == "STYLE")
{continue;}
//all the actions
}
This will stop you assigning css style properties to <html>,<head>,<script> and <style> tags.
```
Andy


----------



## -Fabez- (Jul 28, 2008)

Thanks for the help both of you  One last question, if tag names aren't specified by me or the website developer will they still be included in the loop ?


----------



## andythepandy (Jul 2, 2006)

Yes, they will be unless you add them to the if statement in the loop that checks for unwanted tags.


----------



## -Fabez- (Jul 28, 2008)

Okay then, thank you for your help. I will mark this one solved


----------

