Javascript getElement by href?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10572735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:55:32  来源:igfitidea点击:

Javascript getElement by href?

javascripthrefgetelementsbytagname

提问by Owen

I've got the script below

我有下面的脚本

var els = document.getElementsByTagName("a");
for(var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  el.innerHTML = el.innerHTML.replace(/link1/gi, 'dead link');
}

However this searches through the page and takes about 20 seconds to do it as there are LOTS of links.

然而,这会搜索整个页面并需要大约 20 秒才能完成,因为有很多链接。

However I only need to target the a's that have a specific href, for eg. "http://domain.com/"

但是,我只需要针对a具有特定 的href,例如。“http://domain.com/”

So ideally I'd like to be able to do this in a similar fashion to jQuery, but without using a framework. So something like

所以理想情况下,我希望能够以与 jQuery 类似的方式做到这一点,但不使用框架。所以像

var els = document.getElementsByTagName("a[href='http://domain.com']");

How would I go about doing this so it only searches the objects with that matching href?

我将如何执行此操作,以便它仅搜索具有该匹配项的对象href

回答by rsp

2016 update

2016年更新

It's been over 4 years since this question was posted and things progressed quite a bit.

自从发布这个问题以来已经有 4 年多了,事情有了很大进展。

You can'tuse:

不能使用:

var els = document.getElementsByTagName("a[href='http://domain.com']");

but what you canuse is:

但你可以使用的是:

var els = document.querySelectorAll("a[href='http://domain.com']");

(Note:see below for browser support)

注意:浏览器支持见下文)

which would make the code from your question work exactly as you expect:

这将使您的问题中的代码完全按照您的预期工作

for (var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  el.innerHTML = el.innerHTML.replace(/link1/gi, 'dead link');
}

You can even use selectors like a[href^='http://domain.com']if you want all links that startwith 'http://domain.com':

你甚至还可以使用选择a[href^='http://domain.com'],如果你想,所有的环节开始'http://domain.com'

var els = document.querySelectorAll("a[href^='http://domain.com']");

for (var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  el.innerHTML = el.innerHTML.replace(/link/gi, 'dead link');
}

See: DEMO

见:演示

Browser support

浏览器支持

The browser support according to Can I useas of June 2016 looks pretty good:

根据Can I useas of June 2016的浏览器支持看起来不错:

caniuse.com/queryselector(See: http://caniuse.com/queryselectorfor up to date info)

caniuse.com/queryselector(有关最新信息,请参阅:http: //caniuse.com/queryselector

There is no support in IE6and IE7but IE6 is already deadand IE7 soon will be with its 0.68% market share.

IE6IE7不支持,但 IE6 已经死了,IE7 很快将以其0.68% 的市场份额

IE8is over 7 years old and it partiallysupports querySelectorAll - by "partially" I mean that you can use CSS 2.1 selectorslike [attr], [attr="val"], [attr~="val"], [attr|="bar"]and a small subset of CSS 3 selectorswhich luckilyinclude: [attr^=val], [attr$=val], and [attr*=val]so it seems that IE8 is fine with my examples above.

IE8已经有 7 年历史了,它部分支持 querySelectorAll——“部分”我的意思是你可以使用CSS 2.1 选择器,[attr], [attr="val"], [attr~="val"][attr|="bar"]以及一小部分CSS 3 选择器幸运的是包括: [attr^=val], [attr$=val][attr*=val]所以看起来 IE8 是我上面的例子很好。

IE9, IE10and IE11all supportquerySelectorAll with no problems, as do Chrome, Firefox, Safari, Operaand allother major browser - both desktop and mobile.

IE9IE10IE11支持querySelectorAll,没有问题,ChromeFirefoxSafariOpera所有其他主要浏览器 -桌面和移动设备也是如此

In other words, it seems that we can safely start to use querySelectorAllin production.

换句话说,我们似乎可以安全地开始querySelectorAll在生产中使用了。

More info

更多信息

For more info, see:

有关更多信息,请参阅:

See also this answerfor the difference between querySelectorAll, querySelector, queryAlland queryand when they were removed from the DOM specification.

另见这个答案之间的差额querySelectorAllquerySelectorqueryAllquery当他们从DOM规范删除

回答by Alnitak

Reading and writing the innerHTMLproperty on every element is probably quite expensive and hence causing your slowdown - it forces the browser to "serialize" the element, which you then run through a regexp, and then "deserialize" again. Even worse, you're doing it for everyaelement, even if it doesn't match.

innerHTML在每个元素上读取和写入属性可能非常昂贵,因此会导致您的速度变慢 - 它迫使浏览器“序列化”元素,然后您通过正则表达式运行该元素,然后再次“反序列化”。更糟糕的是,您对每个a元素都这样做,即使它不匹配。

Instead, try looking directly at the properties of the aelement:

相反,尝试直接查看a元素的属性:

var els = document.getElementsByTagName("a");
for (var i = 0, l = els.length; i < l; i++) {
    var el = els[i];
    if (el.href === 'http://www.example.com/') {
        el.innerHTML = "dead link";
        el.href = "#";
    }
}

EDITon modern browsers with much greater W3C conformance you can now use document.querySelectorAll()to more efficiently obtain just the links you want:

在具有更高 W3C 一致性的现代浏览器上进行编辑,您现在可以使用它document.querySelectorAll()来更有效地获取所需的链接:

var els = document.querySelectorAll('a[href^=http://www.example.com/]');
for (var i = 0, l = els.length; i < l; i++) {
    els[i].textContent = 'dead link';
    els[i].href = '#';
}

This is however not so flexible if there are multiple domain names that you wish to match, or for example if you want to match both http:and https:at the same time.

然而,这不是那么灵活,如果有多个域名,你想匹配,或者例如,如果你想同时匹配http:,并https:在同一时间。