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.
You can do it like following using jQuery contain attribute selector.
$('a[href*="/test/"]').attr('href');
use starts with selector
$( "a[href='^/test/'" ).attr( "href" )
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');
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With