JS - Splitting a string and looping through results
As an alternative:
for(element of feedUpdateResponse.split("/")){
do_your_thing();
}
Using for..in
will end up giving you the indices on the array (keys), while for..on
will give you the elements of the array (values).
You can also do:
for ([index, element] of Object.entries(feedUpdateResponse.split("/"))) {
do_your_thing();
}
In the event that you need the index.
The disadvantage is it not being compatible with IE, but for personal projects or a quick automation script it usually does me plenty fine.
Get your array via string.split("/")
. Iterate your array using your method of choice. I prefer Array.forEach()
:
feedUpdateResponse.split("/").forEach(function (item) {
document.getElementById(item).style.visibility = "visible";
});
See the compatibility notes for using .forEach()
in older browsers.
You can use .split()
to split a string on a specified character with the results returned as an array. So then it's just a matter of looping through the array:
// given your existing variable
// feedUpdateResponse = "div1/div2/div3/div4" as set in the
// code in the question, add this:
var a = feedUpdateResponse.split("/"),
i;
for (i = 0; i < a.length; i++) {
document.getElementById("updateAvailable_" + a[i]).style.visibility
= "visible";
}