Reputation: 33
I have a chunk of code here
//function that hides unwanted page elements based on a what is entered in a search bar
function pageSearch() {
//when the function is called it retrieves what is entered in the search bar
//*****************variables*****************\\
var userInput = document.getElementById("boxOfSearching").value;
var fields = [];
//an array of all article tags
fields = document.getElementById("bulletin-course-listings").getElementsByTagName("li");
var holder = "";
var counter = 0;
var childArray = [];
//*****************processing and output*****************\\
//while loop to sort through array elements
while (counter < fields.length)
{
childArray = fields[counter].getElementsByTagName("strong");
holder = childArray[0].innerHTML.toLowerCase();
if (holder.indexOf(userInput) == -1)
{
fields[counter].setAttribute("style", "display:none");
}
else
{
fields[counter].setAttribute("style", "");
}
counter++;
}
}
Now, what is supposed to happen (and what does happen) is when I type something in a text box with an id called boxofsearching (that calls this function on keyup). It searches through a list of elements and grabs what's in the tag. It then compares it to what the user input and if it doesn't contain it then it removes the element.
However, I'm using it on a list that contains several hundred elements. What happens when I type is my browser locks up and the memory usage and CPU usage spike for several seconds and then it finishes. Is there a more efficient way of doing this?
Upvotes: 2
Views: 68
Reputation: 771
Well, your fields should be a global variable, and preferentially a simple JS object instead of a element list, like
fields = [{"obj1"}, {"obj2"}];
The getElementsByTagName
on every keyup may be slowing it down.
Upvotes: 1
Reputation: 700
Are you planning on deleting the actual DOM elements, or just hiding them via CSS as you're doing? If you're not actually deleting them from the DOM, you can retrieve the array of elements once, like this:
var fields = array()
document.onload = function() {
fields = document.getElementById("bulletin-course-listings").getElementsByTagName("li");
}
function pageSearch() { ... }
Then you can remove the definition of fields
in the function. That should improve the performance somewhat.
Upvotes: 2