How to insert a div at a specific position in an array in javascript

I have an array, and when I return my array I get something like this.

arr[0] = <li data="Dummy1" class= "Dummy1"></li>
arr[1] = <li data="Dummy2" class= "Dummy2"></li>
arr[2] = <li data="Dummy3" class= "Dummy3"></li>

      

Now after arr [0] I wanted to insert a div with cursor style

<div style: 'cursor:auto'></div>

      

so my array will look like

arr[0] = <li data="Dummy1" class= "Dummy1"></li>
arr[1] = <div style: 'cursor:auto'></div>
arr[2] = <li data="Dummy2" class= "Dummy2"></li>
arr[3] = <li data="Dummy3" class= "Dummy3"></li>

      

Can someone help me how to achieve this?

+3


source to share


2 answers


you can use this function splice

for array object:

arr.splice(1, 0, "<div style: 'cursor:auto'></div>");

      



This will add the item at index 1, removing 0 items.

+3


source


Use Array.splice () Method : It modifies the contents of the array by removing existing elements and / or adding new elements.



var arr = [];

arr[0] = '<li data="Dummy1" class= "Dummy1"></li>';
arr[1] = '<li data="Dummy2" class= "Dummy2"></li>';
arr[2] = '<li data="Dummy3" class= "Dummy3"></li>';

arr.splice(1, 0, "<div style: 'cursor:auto'></div>");

console.log(arr);
      

Run codeHide result


+1


source







All Articles