Javascript getElement href (JGH)


JGH:   SOLD       




I have 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 so because there are a LOT of links.

But I only need to target the ones that have a specific href, for example . " http://domain.com/ "

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

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

How do I do this so that it only searches for objects matching that href?

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

You cannot use:

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

but what you can use is:

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

(Note: see below for browser support)

which will 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 starting with ' 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');
}

Browser support

Browser support according to Can I use as of June 2016 looks pretty good:

(See:  http://caniuse.com/queryselector  for the latest info)

There is no support in IE6 and IE7 but IE6 is dead and IE7 will be soon with 0.68% market share.

IE8 is over 7 years old and partially supports querySelectorAll - by "partially" I mean you can use CSS 2.1 selectors like [attr], [attr="val"], [attr~="val"], [attr|="bar"] and a small subset of CSS 3 selectors which thankfully includes: [attr^=val], , [attr$=val] and it looks like IE8 is fine with my example above.[attr*=val]

IE9, IE10 and IE11 all support querySelectorAll without issue, as do Chrome, Firefox, Safari, Opera and all other major browsers - both desktop and mobile.

In other words, it seems we can safely start using querySelectorAll in production.

More info
For more info, see:


Post a Comment

Previous Next

نموذج الاتصال