AussieM8 AussieM8 - 5 months ago 21
HTML Question

Looping through DOM elements including span elements

I'm trying to get a function to work but haven't had any luck so thought I would ask a newbie question to the Stackoverflow brains-trust!

Basically, I have a form and I'm looping through all the elements to see if there is a custom data attribute present. If it's there, keep the element visible but if it's not there, hide the element.

When I use the function below, it's looping through all the input fields on the form but it ignores any span or div elements, even if they have the 'data-group' attribute with a value of 'FocusGroup'

function DropDownSelection_Focus(FocusGroup)
{
var elements = frm_FormName.elements;
var el;
for (var i=0, iLen=elements.length; i<iLen; i++)
{
el = elements[i];
var GetGroup = document.getElementById(el.name).getAttribute('data-group');
if (GetGroup != null && GetGroup !='')
{
if (GetGroup == FocusGroup.value)
{
document.getElementById(el.name).style.visibility = 'visible';
}
else
{
document.getElementById(el.name).style.visibility = 'hidden';
}
}
}
}


The span/div elements have both an id and name values so is there a reason why they are being excluded from the loop?

Answer

The element property of FORM object returns a collection of all elements in a form. Elements mean a input, textarea, button or select. Something that support "user action" - can be pressed, selected or etc. If you want to get all elements that have data-group attribute you can use something like this:

var elementsWithGroupAttr = frm_FormName.querySelectorAll("*[data-group]");

frm_FormName is form (the variable from your code snippet).