I’m trying to loop through several thousand javascript elements. Specifically checkboxes and selects. The checkboxes need to be toggled between check/uncheck and selects need to disabled/enabled depending on whether a main checkbox is checked or not.
<script>
function processFormElem(min, max, isChecked) {
for (var i=min; i < max; i++) {
document.getElementById('chkbox_'+i).checked = isChecked;
document.getElementById('select_'+i).disabled = !(isChecked);
}
}
</script>
Check this: <input onchange='processFormElem(0,10000,this.checked);' type='checkbox' value = '0'><br/><br/>
<?php
for ($i=0; $i < 10000; $i++) {
echo "Check: <input type='checkbox' id='chkbox_$i' value = '1'> ";
echo "Select: <select disabled='disabled' id='select_$i'><option selected>1<option>xyz</select><br/>";
}
?>
This code does what’s needed but it’s extremely slow in processing through the form elements, and I can notice the lag. Is there any way to make it faster ?
If your checkboxes and select boxes are all immediately after one another, try using nextElementSibling. The problem is that document.getElementById has to search through each element in the DOM tree to find the one with the matching ID (although the underlying implementation might use hash tables or something to improve ID lookup performance)
Either way, using nextElementSibling lets you walk through the elements as you would through a tree, saving you seek time.
For example:
EDIT:
As David notes below, not all browsers support nextElementSibling. You can hack around that using nextSibling.
Instead of:
Do:
That being said, the browsers that don’t support nextElementSibling are becoming less and less common every day, and the nextSibling solution comes with plenty of its own overhead. It’s up to you (or potentially your boss) if you want to support older browsers.