2012-05-29

Access all elements in a page and set an attribute/style for all of them

Here is how you can get all the elements in a page and apply an attribute/style for all of them using javascripts. Here, as for the example, I’ll change the background color of all elements. Following is the complete code for that. I will explain one by one after that.

<script>
window.onload=function test()
{
var all = document.getElementsByTagName('*');

for(var i=0;i<all.length;i++)
{
all[i].style.backgroundColor = "Red";
}
}
</script>

I’m calling the above function on window.onload event, so it will get called automatically when the page loads.

document.getElementsByTagName('*');

Above line returns a collection of HTML elements. For the tag name, I’ve passed * (Which is the wildcard character for ‘all’) so it will return all the HTML elements within the page.

for(var i=0;i<all.length;i++)
{
all[i].style.backgroundColor = "Red";
}
}

Then I’m going through that collection accessing each element and applying the style for each of them. Here I’m changing the background color of each element. Not only the style, you can change/get/set any property you would like.

No comments: