2

Why pop() method does not work? I have this error

Uncaught TypeError: undefined is not a function

How can I use array methods on documents links to remove or add elements? Thanks

<!doctype html>
<html>
<head>
<meta charset="UTF-8">  
</head>
<body>
<div>
<nav class="mainNav" id="mainNav">
<ul>
<li><a href="http://en.wikipedia.org/wiki/New-age_music" title="New Age"  target="_blank" > New Age </a> 
<ul class=subNav>
<li><a href="DevaPremal.html" title="Deva Premal" target="_blank"> Deva Premal</a></li>
<li><a href="http://www.karuneshmusic.com/" title="Karunesh" target="_blank">Karunesh</a></li>
<li><a href="http://www.luboistok.ru/" title="Oles" target="_blank">Oles</a></li>
</ul>
</li>

<script type="text/javascript">
function addLinks()
{
    var allLinksArray = document.links;
    var singersArray = allLinksArray.pop();
    console.log(allLinksArray.length);
    console.log(singersArray.length);
}

addLinks();
</script>
</body>
</html>
0

1 Answer 1

1

That's because document.links returns HTMLCollection and not a simple array.
So you need to convert HTMLCollection to real array.

An example how to do this is described here.

You need:

var allLinksArray = Array.prototype.slice.call( document.links );

All for you - even working code on jsfiddle ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Or the shorter [].slice.call(document.links)
Right, but with Array it is more easy to understand :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.