Changing default href to data-href using js

Viewed 24

".setAttribute()" etc. I used some values but without success.

href > data-href

by default there is an href element

"<a class="wp-block-post-excerpt__more-link" href="#link" tabindex="0">View Details</a>"

I want to change this element to data-href using js. Also, I don't want to add another one.

"<a class="wp-block-post-excerpt__more-link" data-href="#link" tabindex="0">View Details</a>"

I am using the following js code, both href and data-href are added and I want to remove it as a link.

$('a[href]').each(function() { 
 $(this).attr('data-href', $(this).attr('href'));
});
1 Answers

Simply using vanilla Javascript:

  • Grab the href attribute, set it in a variable oldHref
  • Remove href using removeAttribute
  • Add new data-attribute of that oldHref variable using setAttribute

let link = document.querySelector('.wp-block-post-excerpt__more-link');
let oldHref = link.href;
link.removeAttribute('href');
link.setAttribute("data-href", oldHref);
<a class="wp-block-post-excerpt__more-link" href="#link" tabindex="0">View Details</a>

Related