使用getElementsByTagName查找变量中的所有href

问题描述 投票:0回答:2

在一个变量我拿着HTML源代码,我从DB获得。我想通过搜索所有“a href”属性的内容并将它们列在表格中。

现在我在这里找到了如何在DOM中搜索它(如下所示),但如何使用它在变量中搜索?

var links = document.getElementsByTagName("a").getElementsByAttribute("href");

目前有这个,这是由RegEx搜索,但它不能很好地工作:

matches_temp = result_content.match(/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’&quote]))/ig);

在result_content中我持有HTML Source。

javascript getelementsbytagname
2个回答
0
投票

getElementsByTagName返回一个没有名为getElementsByAttribute的方法的节点列表,但只有你有DOM访问权限时才会返回

没有DOM(例如node.js)

const hrefRe = /href="(.*?)"/g;
const urlRe = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’&quote]))/ig;

 
const stringFromDB = `<a href="http://000">000</a>
Something something <a href="http://001">001</a> something`

stringFromDB.match(hrefRe).forEach(
 (href) => console.log(href.match(urlRe)[0] ) 
);

// oldschool: 
// stringFromDB.match(hrefRe).forEach(function(href) {  console.log(href.match(urlRe)[0] )      });

在这段代码中,我首先创建了一个DOM片段。此外,我只获得了一个以href开头的锚点

请注意getAttribute,以便浏览器不会尝试解释URL

使用正则表达式,如果您只想匹配SPECIFIC类型的href:

const re = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’&quote]))/ig;

const stringFromDB = `<a href="http://000">000</a>
<a href="http://001">001</a>`

let doc = document.createElement("div");
doc.innerHTML = stringFromDB

doc.querySelectorAll("a[href]").forEach(
  (x) => console.log(x.getAttribute("href").match(re)[0])
);

没有正则表达式

const stringFromDB = `<a href="http://000">000</a>
<a href="http://001">001</a>`

let doc = document.createElement("div");
doc.innerHTML = stringFromDB

doc.querySelectorAll("a[href]").forEach(
 (x) => console.log(x.getAttribute("href")) 
);

0
投票

首先,您不应该使用RegEx来解析HTML。 This answer解释了原因。

其次,你正在使用getElementsByAttribute错误 - 它完全按照它所说的内容并按属性获取元素。你应该在querySelectorAll的所有元素上使用href,然后在map中使用href

var hrefs = document.querySelectorAll("a[href*=http]");
var test = Array.prototype.slice.call(hrefs).map(e => e.href);
console.log(test);
<a href="http://example.com">Example</a>
<a href="http://example1.com">Example 1</a>
<a href="http://example2.com">Example 2</a>
<a href="http://example3.com">Example 3</a>
© www.soinside.com 2019 - 2024. All rights reserved.