1

I tried this:

var els = document.querySelectorAll('a[href*="dabbing-through-the-snow"]')

There are 36 elements on the page with links like this one:

https://www.teepublic.com/t-shirt/3298777-funny-maltese-dabbing-through-the-snow-dab-christm?store_id=138163.

However, my code selected all the links on the page, I think.

How to ONLY select the links that have the text, for example, dabbing-through-the-snow?

alexchenco
  • 53,565
  • 76
  • 241
  • 413
  • @Satpal Yes, I want to select all the anchor tags that contain `dabbing-through-the-snow` in their URL. – alexchenco Oct 12 '18 at 04:56
  • 1
    Your code should work then – Satpal Oct 12 '18 at 04:58
  • can you provide us the html code? your code is definitely correct – novalagung Oct 12 '18 at 05:02
  • @alexchenco Here is a list of css selectors reference that you can use within your code: https://www.w3schools.com/cssref/css_selectors.asp If you use * it matches with all the occurances and if you use ~ it will only match the whole word reference. You also can try using ^ or $ to match the beginning or ending. I'm not sure what exactly you seek but this might help :) – dRoyson Oct 12 '18 at 05:02
  • I think this will help you. [check the link](https://stackoverflow.com/questions/37098405/javascript-queryselector-find-div-by-innertext) – Pallamolla Sai Oct 12 '18 at 05:05
  • Check the link below once. I think it will help you https://stackoverflow.com/questions/3813294/how-to-get-element-by-innertext – Pallamolla Sai Oct 12 '18 at 05:08

2 Answers2

3

You can use document.querySelectorAll([attribute*=value]) to select all elements with the attribute containing the value string, so your code should be correct.

var els = document.querySelectorAll('a[href*="dabbing-through-the-snow"]');
var anchors = document.querySelectorAll('a');
console.log("Anchors:", anchors.length, "Matched Anchors:", els.length);
<a href="">1</a>
<a href="https://www.teepublic.com/t-shirt/3298777-funny-maltese-dabbing-through-the-snow-dab-christm?store_id=138163">2</a>

You may also want to traverse through all the anchor elements with a for loop if you have more complicated criteria.

var anchors = document.querySelectorAll("a");
var href = "dabbing-through-the-snow";
var found = [];

for (var i = 0; i < anchors.length; i++) {
  if (anchors[i].href.includes(href)) {
    found.push(anchors[i]);
  }
}
console.log("Anchors:", anchors.length, "Matched Anchors:", found.length);
<a href="">1</a>
<a href="https://www.teepublic.com/t-shirt/3298777-funny-maltese-dabbing-through-the-snow-dab-christm?store_id=138163">2</a>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

You can try following code to get href with string :

const $aHref = $("a").filter((index, value) => $(value).attr('href').match(/\/dabbing-through-the-snow\//));
const urlString = $.map($aHref, data => $(data).attr('href'));
console.log(urlString);
PHP Geek
  • 3,949
  • 1
  • 16
  • 32