27

Let I've some elements with href=/href_value/attribute. How to get all elemenets such that their href attribute has the href_value value?

  • You mean something like this? http://stackoverflow.com/questions/303956/select-a-which-href-ends-with-some-string – metakermit Apr 24 '14 at 13:15

4 Answers4

27

If you have the luxury of neglecting IE 7 or lower, you can use:

document.querySelectorAll("[href='href_value']");
reaxis
  • 1,361
  • 12
  • 11
21

Maybe you need to get all the elements whose href value contain your specific href_value? If so, try:

document.querySelectorAll('[href*="href_value"]');
Community
  • 1
  • 1
Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30
7

Heres a version that will work in old and new browsers by seeing if querySelectorAll is supported

You can use it by calling getElementsByAttribute(attribute, value)

Here is a fiddle: http://jsfiddle.net/ghRqV/

var getElementsByAttribute = function(attr, value) {
    if ('querySelectorAll' in document) {
        return document.querySelectorAll( "["+attr+"="+value+"]" )   
    } else {
        var els = document.getElementsByTagName("*"),
            result = []

        for (var i=0, _len=els.length; i < _len; i++) {
            var el = els[i]

            if (el.hasAttribute(attr)) {
                if (el.getAttribute(attr) === value) result.push(el)
            }
        }

        return result
    }
}
bottens
  • 3,834
  • 1
  • 13
  • 15
6

You can use document.querySelectorAll to search for all elements that match a CSS selector. This is supported by all modern browser versions.

In this case:

var elements = document.querySelectorAll('[href="href_value"]');
RoToRa
  • 37,635
  • 12
  • 69
  • 105