我想用 Javascript 替换 link 的 H2 标签
I want to replace H2 tag by link with Javascript
我想将 link 的 H2 标签替换为 Javascript。
所以标签看起来像:
<h2>Categories</h2>
我期望输出:
<a href="#">Categories</a>
我该怎么做?可能吗?
我尝试过但没有成功的代码:
$("#categories").find("h2").replaceWith($('<a href="#"></a>'));
使用 replaceWith 和 createElement。
const h2s = document.querySelectorAll("h2");
h2s.forEach(function (elem) {
const anchor = document.createElement("a");
anchor.href = "#";
anchor.textContent = elem.textContent;
elem.replaceWith(anchor);
});
<h2>Hello</h2>
<h2>There</h2>
我想将 link 的 H2 标签替换为 Javascript。
所以标签看起来像:
<h2>Categories</h2>
我期望输出:
<a href="#">Categories</a>
我该怎么做?可能吗?
我尝试过但没有成功的代码:
$("#categories").find("h2").replaceWith($('<a href="#"></a>'));
使用 replaceWith 和 createElement。
const h2s = document.querySelectorAll("h2");
h2s.forEach(function (elem) {
const anchor = document.createElement("a");
anchor.href = "#";
anchor.textContent = elem.textContent;
elem.replaceWith(anchor);
});
<h2>Hello</h2>
<h2>There</h2>