Reputation: 61
I was wondering if there was any way to get a value of an array, based on a string, and display the next value in the array.
<p id="current">page1</p>
<p id="next"></p>
<script>
var page = ["page1", "page2", "page3", "page4", "page5"];
if(document.getElementById("current") == page[0]){
document.getElementById("next").innerhtml = page[1]
};
</script>
That's what I have as the general idea. However, it would be a lot of if statements, and it wouldn't look pretty. So I was wondering if there would be a way to replicate this sort of function, without it including too many if statements.
Upvotes: 0
Views: 198
Reputation: 7161
Combining code with comments makes for a great way to learn:
// This is the list of pages you have.
var pages = ["page1", "page2", "page3", "page4", "page5"];
// We use the innerText attribute of the #current node to find out
// what the current page is as a string.
var current = document.getElementById("current").innerText;
// Use the indexOf method of pages to get the index of the current
// page in the list of pages.
var index = pages.indexOf(current);
// Now, check if there is a next page. We do so by checking if current
// is not the last page in the list, or rather, there is at least one
// more page in the list.
if (index < pages.length - 1) {
// If so, we set next to that page. Note that you can put an
// expression for the key when using bracket notation here!
var next = pages[index + 1];
} else {
// Otherwise, use other text.
var next = "No more pages :(";
}
// Now set the innerHTML of the #next node to the value of next.
document.getElementById("next").innerHTML = next;
Upvotes: 2
Reputation: 12127
you can use indexOf()
function when you multiple values in array.
var currentIndex = page.indexOf(document.getElementById("current").textContent);
if(currentIndex > -1){
if((currentIndex + 1) == page.length){
// for last element
}else{
document.getElementById("next").innerhtml = page[currentIndex + 1];
}
}
Upvotes: 0
Reputation: 339
Just include a for statement
<p id="current">page1</p>
<p id="next"></p>
<script>
var page = ["page1", "page2", "page3", "page4", "page5"];
for (i=0;i=page.length-1;i++) {
if(document.getElementById("current") == page[i]){
document.getElementById("next").innerhtml = page[i+1]
};
}
Upvotes: 0
Reputation: 4221
You could use the .indexOf
method (more info) to find the array index of the element you're looking for.
Fiddle: http://jsfiddle.net/0fu3dydy/
JavaScript
var page = ["page1", "page2", "page3", "page4", "page5"];
var currentPageIndex = page.indexOf(document.getElementById("current").innerHTML);
if (currentPageIndex < page.length - 1) {
document.getElementById("next").innerHTML = page[currentPageIndex + 1];
} else {
// Do something when the current element is also the last
}
Upvotes: 0