Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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've come up with so far. I know that it can find /test/ but I'm struggling with returning the full href value. Any ideas?

function() {
    var htmlString = $('body').html().toString();
    var index = htmlString.indexOf("/test/");
    if (index != -1)
        return index.closest('div').find('a').attr('href');
}

HTML:

<div>
    <a href="/test/123/">Test</a>
</div>

Thanks in advance.

like image 478
aphextwig Avatar asked Jan 29 '16 12:01

aphextwig


4 Answers

You can do it like following using jQuery contain attribute selector.

$('a[href*="/test/"]').attr('href');
like image 137
Ibrahim Khan Avatar answered Nov 20 '22 16:11

Ibrahim Khan


use starts with selector

$( "a[href='^/test/'" ).attr( "href" )
like image 5
gurvinder372 Avatar answered Nov 20 '22 17:11

gurvinder372


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');
});
like image 1
Neil Atkinson Avatar answered Nov 20 '22 15:11

Neil Atkinson


You can use CSS “Substring Matching Attribute Selectors” to search the word in a string .

  $("body a[href='^/test/'").attr("href")

[att] Represents an element with the att attribute, whatever the value of the attribute.

[att=val] Represents an element with the att attribute whose value is exactly "val".

[att~=val] Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces). Also if "val" is the empty string, it will never represent anything.

[att|=val] Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D). This is primarily intended to allow language subcode matches (e.g., the hreflang attribute on the a element in HTML) as described in BCP 47 ([BCP47]) or its successor. For lang (or xml:lang) language subcode matching, please see the :lang pseudo-class.

Reference : Reference link

like image 1
Suraj Rawat Avatar answered Nov 20 '22 16:11

Suraj Rawat