这可以通过querySelector 和el.removeAttribute 轻松完成:
let removeHrefTarget = document.querySelector(".removeatag a"); //select the element that has the according class
removeHrefTarget.removeAttribute("href"); //remove the href-attribute from that element
但您可能需要考虑是否有多个元素要从中删除 href。为此,您可以使用querySelectorAll,它会返回符合您的条件的所有元素的节点列表。然后遍历列表中的所有元素并删除每个元素的属性:
let removeHrefTargets = document.querySelectorAll(".removeatag a"); //select all elements that have the according class
removeHrefTargets.forEach((el) => { //loop through each of these elements
el.removeAttribute("href"); //remove the href attribute
})
编辑:
如果您想更进一步,您还可以创建一个可重用的函数。每当您想从任何元素中删除任何属性时都可以使用它。
const removeAttribute = (selector, attribute) => {
let removeAttributeTargets = document.querySelectorAll(selector); //select all elements that have the according class
removeAttributeTargets.forEach((el) => { //loop through each of these elements
el.removeAttribute(attribute); //remove the href attribute
});
};
您可以使用任何选择器(例如 #id 或 .class 或标签)调用此函数,如下所示:
removeAttribute(".myclass", "style");
希望这会有所帮助:)