2

I'm trying to crete 3 HTML collections containing all my links on a page, so I can attach 3 separate function to each categories of links. My first HTML collection is "header links", the second is "footer links" and the third is "all other links". I need to attach link tracking functions and other elements as well.

Creating the first two collections is fairly easy as I can do document.getElementById('header'); and document.getElementById('footer'); and then this.getElementsByTagName('a'); However, getting the third collection of "all other links" is a bit more tricky. There isn't a clean div that contains just the "middle" of the page, and there are links outside the header and footer that are also difficult to single out. I wish I could do something like allLinks = document.linnks, and then filter out of that all the links already present in the first and second HTML collections.

Any way to do that ? Ideally I would like to avoid loading more libraries and pure JS would be welcome

Thanks !

4

1 回答 1

0

您可以将节点列表转换为数组,然后用于filter()拉出已经在其他列表之一中的链接:

var hdr = document.getElementById('header');
var hlinks = arrayOf(hdr.getElementsByTagName('a'));

var ftr = document.getElementById('footer');
var flinks = arrayOf(ftr.getElementsByTagName('a'));

var others = arrayOf(document.getElementsByTagName('a')).
filter(
  function(element) {
    return (hlinks.indexOf(element) < 0) && (flinks.indexOf(element) < 0);
  }
);

function arrayOf(nodelist)
{
  var result = [];
  for ( var i = 0; i < nodelist.length; ++i )
    result.push(nodelist.item(i));

  return result;
}

示例:http ://codepen.io/paulroub/pen/ikebh

如果Array.prototype.filter()您需要支持缺少.

于 2014-06-02T15:39:21.100 回答