简体   繁体   中英

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?

如果您可以忽略 IE 7 或更低版本,则可以使用:

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

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

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

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
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM