skip to Main Content

I have an array with 20 objects, only 10 of them are displayed in my website page, but I’d like to display the next 10 when clicking a button. I created a function that works and gets called when clicking said button but it only works in the console and I can’t return it.

This is the button that calls the function:

<button id="next" onclick="nextTwo()">2</button>

and this is the function (the objList is the array containing 20 objects):

function nextTwo() {
    const page = 2;
    const step = 10;
    const start = page * step - step;
    const end = start + step;

    const nextobj = objList.slice(start, end);
    console.log(nextobj);
    return nextobj;
}

I tried adding a for loop and adding
document.getElementbyId('x_list').innerHTML = nextobj
but nothing seems to be working.

2

Answers


  1. innerHTML expects a string to be assigned. You need to convert the secondpage array into a formatted string that can be displayed in the HTML.

        // Assuming you have a container element with id 'x_list' to display the objects
        const container = document.getElementById('x_list');
        
        // Clear the container before adding the new content
        container.innerHTML = '';
        
        // Convert the array to an HTML string and append it to the container
        nextobj.forEach(obj => {
            const item = document.createElement('div');
            item.textContent = obj.title; // Assuming each object has a 'title' property to display
            container.appendChild(item);
        });
    
    Login or Signup to reply.
  2. I have tried your code and it works fine Here is a fiddle where the return statement in your code seems to be working fine. Also check that your function closing braces are set properly and check your console for "illegal return statement" error. But code works fine.

        const objList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ,20]
    
    function nextTwo() {
        const page = 2;
        const step = 10;
        const start = page * step - step;
        const end = start + step;
    
        const nextobj = objList.slice(start, end);
        //console.log(nextobj);
        return nextobj;
    } 
    
    const nextobj = nextTwo()
    console.log(nextobj)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search