Home > Software design >  Changing default href to data-href using js
Changing default href to data-href using js

Time:09-26

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

href > data-href

by default there is an href element

"<a 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 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'));
});

CodePudding user response:

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  href="#link" tabindex="0">View Details</a>

  • Related