How to take the href of an element and also assign it as id of it without Sharp (#)?

Asked

Viewed 3,405 times

0

I’m wearing a shortcode in Wordpress that only gives me the possibility to insert the following attributes:

<a href="#anatomia" target="_self" class="dt-sc-button small">Inscreva</a>
<a href="#anatomia" target="_self" class="dt-sc-button small">Saiba mais</a>

I’d like to take the attribute then href and insert it as the element’s ID. Since there may be more than one element (7 to begin with), I thought I’d put it into one foreach to repeat this for all elements.

Another thing ... I thought I’d use the class dt-sc-button to restrict the application to these elements.

  • 2

    $('.dt-sc-button'). each(Function(){ this.id = $(this). attr('href'). Slice(1); }); <- I think this will do the trick

  • Why you need to insert Ids into these elements?

  • To make different calls for each course. Different price, different date and location etc ...

1 answer

1


If you have a class for those elements you can use $('.dt-sc-button') and then stick them with a .each().

To get the href you can use $(this).attr('href') within that .each() and then just take out the first character. The .slice(1) does that.

Code suggestion:

$('.dt-sc-button').each(function () {
    this.id = $(this).attr('href').slice(1);
});
  • Has two href wrapped for each class. How not to assign id to the second button?

  • @Marcosvinicius can show what HTML looks like in this case?

  • In fact, just assign another href to the second button. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.