Jump to content

get all elements on a page...


RIRedinPA

Recommended Posts

Is there a way to make an array of all elements on a page?

 

I tried this

 

//hide initial elements
var bodytag = document.getElementsByTagName("body");
var bodyelements = bodytag[0].children
for (var e=0; e<bodyelements.length; e++) { 
alert(bodyelements[e].tagName);
}

 

but this only returns the top child element of body (in this case a div). I'm thinking I'll need to use some recursive check to see if the element returned has any children and push them into an array until I have them all...

Link to comment
Share on other sites

Here's a function that finds all the elements with a certain class name. You should be able to easily modify it to just get every element.

function getElementsByClassName(classname, node) {
if (!node){
	node = document.getElementsByTagName("body")[0];
}
var a = [];
var re = new RegExp('\\b' + classname + '\\b');
var els = node.getElementsByTagName("*");
for (var i=0,j=els.length; i<j; i++){
	if(re.test(els[i].className)){
		a.push(els[i]);
	}
}
return a;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.