jQuery - Find href that contains a value and return the full value

前端 未结 5 2093
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 01:12

I\'d like to search the body for an href that contains /test/. I then want to return the entire href value e.g. /test/123/.

Below is what I

5条回答
  •  臣服心动
    2021-01-06 01:46

    You're using jQuery so use the "attribute contains selector" (https://api.jquery.com/attribute-contains-selector/) and retrieve the href values using "attr" (http://api.jquery.com/attr/).

    The following line of code will return all a elements with an href containing the text "/test/".

    var matchingElements = $("a[href*='/test/']")
    

    ...and the following code will return an array of their href attributes.

    var hrefs = matchingElements.map(function(index, element) {
        return $(element).attr('href');
    });
    

提交回复
热议问题