how can i add a id to my href link with jquery?

Viewed 1536

So, i think it's really simple but i don't find a right solution

actually my links looking like this:

<a href="/kfhdsh/kfhdh">Link 1</a>
<a href="/kfhdsh/kfhdh">Link 2</a>
<a href="/kfhdsh/kfhdh">Link 3</a>

How can i add automatically the same ID behind the Link?

Like this:

<a href="/kfhdsh/kfhdh#ID">Link 1</a>
<a href="/kfhdsh/kfhdh#ID">Link 2</a>
<a href="/kfhdsh/kfhdh#ID">Link 3</a>

Thanks for any help!

2 Answers

You can do this by providing a function to attr(). The function will accept the current value of the attribute, and you can return the new value to use after appending the URL fragment, like this:

$('a').attr('href', function(i, href) {
  return href + '#ID';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="/kfhdsh/kfhdh">Link 1</a>
<a href="/kfhdsh/kfhdh">Link 2</a>
<a href="/kfhdsh/kfhdh">Link 3</a>

Note that you could also use prop() for this, but the important difference is that prop() will convert the value to an absolute URL, whereas attr() will retain the relative path.

Is this what you want?

$().ready(function() {
  $("a.link").attr("href", $("a.link").attr("href") + "#ID")
})
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<a class="link" href="/kfhdsh/kfhdh">Link 1</a>
<a class="link" href="/kfhdsh/kfhdh">Link 2</a>
<a class="link" href="/kfhdsh/kfhdh">Link 3</a>

Related