Give this a try:
var spanArray = document.getElementsByTagName('span');
for (var i=0; i<spanArray.length; i++) {
if(spanArray[i].innerHTML.toUpperCase() === 'CHICKEN')
{
alert(spanArray[i].parentNode.className);
break;
}
}
While I usually work with jQuery, the code above seems to function well in the provided fiddle: http://jsfiddle.net/FranWahl/fCzYc/2/ (Updated with suggested break;
after match)
You can enhance type checking for the parentNode
to ensure it is an li
and so on, but this should give you a good starting point.
As for efficiency in larger documents, that's something I'm not entirely sure about.
Edit
After reviewing some comments, I have updated my code above to include the recommended break by ajax333221.
Dennis suggested that it would be better to call getElementByTagName
on the ul
.
Since you may have an li
without a ul
, I separated this code as I am unsure if there are ul
tags present in the OP's scenario.
Code for querying against each ul
(jsFiddle here)
var ulArray = document.getElementsByTagName('ul');
var parentFound = false;
for (var i = 0; i < ulArray.length; i++) {
var spanArray = ulArray[i].getElementsByTagName('span');
for (var i = 0; i < spanArray.length; i++) {
if (spanArray[i].innerHTML.toUpperCase() === 'CHICKEN') {
alert(spanArray[i].parentNode.className);
parentFound = true;
break;
}
}
if(parentFound)
{
break;
}
}