Home > Mobile >  How to display the added element in an array in my html document?
How to display the added element in an array in my html document?

Time:07-05

What I'm trying to do here is to display only the added element in the array on the HTML page? But whenever I add an element using the unshift array method it displays other elements of the array too.

let greetings = ["I", "Hi", "Hello"];
document.getElementById("hello").innerHTML = greetings;

greetings.unshift("Hey");
document.getElementById("hello").innerHTML = greetings;
<h3 id="hello"></h3>

CodePudding user response:

For display the Last Element you add in the array you only need this code:

    <h3 id="hello"></h3>
    <script type="text/javascript">
        
        ;(function(){

            //array values
            var list = ["Hi", "Hello", "Good Morning"];

            //Get the id
            const helloList = document.getElementById('hello');

            //Get the Last Value of Array
            const lastValue = list.length;

            //add a new value for the array from the last position
            //If you need change for unshift for add from the frist position
            list.push("Good Night");

            //Remove and Create a variable with the last value from array
           //If you want show the first value of array inform the key position equal 0
            var valueList = list[lastValue];

            //For select the First Position use shift()
            list.pop();

            //show the values from array
            //helloList.textContent = list.join(", ")   " and "   valueList;

            //Show the last value add in the array
            helloList.textContent = valueList;

        })()


    </script>

CodePudding user response:

The unshift() method adds one or more elements to the beginning of an array....

So after running greetings.unshift("Hey"); you end up with greetings being ["Hey","I","Hi","Hello"];

CodePudding user response:

to only display the new element ("Hey") you would use greetings[0] to get the first element of the array

  • Related