-2

I have this piece of codes:

<a href="https://api.whatsapp.com/send?phone=" data-ga-label="666666666" target="_blank"></a>

I want to select this a tag with jquery based-on "data-ga-label" attribute that have a 666666666 value and change its href. How it's possible with jquery? Thank you.

  • You can use the [attribute selector](https://api.jquery.com/attribute-equals-selector/) or see [this](https://stackoverflow.com/q/2487747/4202224) question coping with your problem – empiric Jul 13 '18 at 11:03
  • `$("#setAnId").attr("href", "https://api.whatsapp.com/send?phone=" + $(this).attr('data-ga-label'));` – urbz Jul 13 '18 at 11:06

3 Answers3

2

You can add selectors for custom data like below, and then change the href attribute of the link.

$('a[data-ga-label="666666666"]').attr('href', 'https://stackoverflow.com/');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://api.whatsapp.com/send?phone=" data-ga-label="666666666" target="_blank">Link</a>
Henkan
  • 310
  • 2
  • 10
0

In jQuery, you can use the attribute equals selector to select the element. You can then use the attr function to change the href location.

You can also do this in one line, as @Henkan does in his answer. I just split it up to explain what each step does.

Example:

// This selects the element using the attribute equals selector
let el = $("a[data-ga-label='666666666']");

// This modifies the href using the attr function
$(el).attr("href", "google.com");

// Show updated link
console.log($(el).attr("href"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://api.whatsapp.com/send?phone=" data-ga-label="666666666" target="_blank"></a>
JoshG
  • 6,472
  • 2
  • 38
  • 61
0

$('a[data-ga-label="666666666"]').attr('href', 'https://stackoverflow.com/');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="https://api.whatsapp.com/send?phone=" data-ga-label="666666666" target="_blank">Link</a>
Avani Somaiya
  • 348
  • 2
  • 7