Javascript slice() is not a function with my list of li elements

9k Views Asked by At

How can I transform the following jquery to javascript?

iElement.children('li')
.css({ "background": "#DDD" })
.slice(0, 1)
.css({ "background": c.col });

IElement.children('li') returns the following:

 [li.point, li.point, li.point, li.point, li.point]

where iElement is a ul.

The problem comes in with the slice(). iElement is an array of objects but I get an error saying that whatever.slice() is not a function

I am trying to write a password strength directive for my angularjs app.

2

There are 2 best solutions below

1
On BEST ANSWER

You get this Exception because you were trying to call an Array method (.slice()) over a nodeList which is not an array.

You have to treat this nodeList as an array, you can :

  • Either convert it with Array.from() method before calling .slice().
  • Or call it like this: Array.prototype.slice.call(IElement.children('li'));
0
On

Seems like it is just setting the first element to a different color:

elements = document.querySelectorAll('ul#iElement > li')
c = { col:'#ABC' }

for (var i = 1; i < elements.length; i++)
    elements[i].style.background = '#DDD'
  
if (elements[0]) elements[0].style.background = c.col
<ul id='iElement'>
  <li> 1 </li>
  <li> 2 </li>
  <li> 3 </li>
  <li> 4 </li>
</ul>