简体   繁体   English

使用正则表达式对页面上的所有链接进行JavaScript

[英]JavaScript all links on a page with regex

I'm trying to extract all links on a web page that has the following markup: 我正在尝试提取具有以下标记的网页上的所有链接:

<a href="/item/0/100">0</a>
<a href="/item/1/100">2</a>
<a href="/item/2/100">3</a>
<a href="/item/3/100">4</a>
<a href="/item/4/100">5</a>

Basically returning all the /item... paths. 基本上返回所有/item...路径。 I have the dom object that contains this. 我有包含此对象的dom对象。 Any idea how to do this? 任何想法如何做到这一点?

Thanks! 谢谢!

EDIT: Using jQuery with Map returns (truncated) 编辑:使用jQuery与地图返回(被截断)

    http:undefined
    { '0': '/item/200/13/0',
      '1': '/item/200/1/0',
      '2': '/item/200/4/0',
      '3': '/item/200/5/0',
      '4': '/item/200/11/0',
      length: 4,
      prevObject: 
       { '0': 
          { _ownerDocument: [Object],
            _childNodes: [Object],
            _attributes: [Object],
            _nodeName: 'a',
            _childrenList: null,
            _version: 3,
            _nodeValue: null,
            _parentNode: [Object],
            _readonly: false,
            _tagName: 'a',
            _created: true,
            _attached: true,
            _attachedToDocument: true },
         '1': 
...

Newer browsers: 较新的浏览器:

var links = document.querySelectorAll('a[href^="/item/"]');

Older browsers: 较旧的浏览器:

var links = [];
var elements = document.getElementsByTagName('a');

for (var i = 0; i < elements.length; i++) {
    var a = elements[i];

    if (a.getAttribute('href').indexOf('/item/') === 0) {
        links.push(a);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM