Home > front end >  How to get href using innertext and regex
How to get href using innertext and regex

Time:02-12

How to get Href from the <a> tag.

how to get href link using selectors, I have tried like below but it didn't work.

expected to get "www.test.com/all_reviews"

var a = document.querySelectorAll("a[href =*'all_reviews'*]")
console.log(a)
<a href="www.test.com/all_reviews">All Reviews</a>
<a href="www.test.com/all_reviews/altered">All Reviews</a>

CodePudding user response:

You could use the jquery :contains() selector like this:

 $("a:contains(All Reviews)") 

See a code example and read more about it here: https://api.jquery.com/contains-selector/

CodePudding user response:

To access the href you should use getAttribute of the selected element

let anchors = document.querySelectorAll('a[href*="all_reviews"]');
let link = null;
Array.from(anchors).forEach(element => {
    let pattern = /all_reviews$/;
    let url = element.getAttribute('href');
    if(pattern.test(url)) {
      link = url;
    }
});

console.log(link);
<a href="www.test.com/all_reviews">All Reviews</a>
<a href="www.test.com/all_reviews/altered">All Reviews</a>

You can use a Regular expression which check if the link and with all_reviews as the second link all_reviews is not at the end of the URL.

  • Related