Home > database >  remove/add element href attribute by its unique path
remove/add element href attribute by its unique path

Time:09-29

I have a tag that looks like this:

<a class="btn btn-default" href="Edit/44"><i class="fa fa-pencil"></i>...</a>

I want to remove a later re-add the href attribute to the element with this specific path("Edit/44"), but it's its only unique identifier. How could I achieve this?

CodePudding user response:

You can get the element to start with using an attribute selector ([href="Edit/44"] in this case) with querySelector:

const element = document.querySelector(`[href="Edit/44"]`);

Then you might move it to a data-* attribute before clearing it:

element.setAttribute("data-href", element.href);
element.removeAttribute("href");

You can either keep a reference to element or find it later the same way, but with a different attribute name, then put it back:

const element = document.querySelector(`[data-href="Edit/44"]`);
element.setAttribute("href", element.getAttribute("data-href"));
element.removeAttribute("data-href");
  • Related