Skip to content Skip to sidebar Skip to footer

How To Get All Elements With A Specified Href Attribute

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?

Solution 1:

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

document.querySelectorAll("[href='href_value']");

Solution 2:

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

document.querySelectorAll('[href*="href_value"]');

Solution 3:

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'indocument) {
        returndocument.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
    }
}

Solution 4:

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"]');

Post a Comment for "How To Get All Elements With A Specified Href Attribute"