Loop to find ul tag with correct id

I'm working on building a script that will loop through all ul's on the page and grab the one with the correct id, but am having slight difficulties.  Any thoughts:

var ul = document.getElementsByTagName("ul");
var polite = ["input1", "input2", "input3"];
for(var u=0; u<ul.length; u++) {
	for(var p=0; p<ul.attributes.length; p++) {
		if(ul[p].getAttribute("id") == polite[p]) {
			polite = ul[p];
		}
	}
}
console.log(polite);
var politeLoads = polite.getElementsByTagName("input");

Open in new window

LVL 1
pingeyegAsked:
Who is Participating?
 
hieloCommented:
ids are supposed to be unique throughout the document, so just loop through your list of ids. Try:
var polite = ["input1", "input2", "input3"];
var i=-1,limit=polite.length;
while(++i<limit)
{
	var element=document.getElementById(polite[i]);
	if(element)
	{
		alert("Found " + polite[i] + ": <" +element.tagName +">" );
	}
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.