假设我们有这个 html:
<div class="some-class">This is the content</div>
<h2 class="some-class">This is to be replaced</div>
在 jquery 中,我们可以使用以下命令替换 h2 的内容:
$('h2.some-class').html('string to replace');
这将替换 h2.some-class 而不会更改 div.some-class 的内容。现在,当前页面没有为此实例使用框架或 jquery 的奢侈 - 只有 javascript。
我们如何替换 带有特定类别的标签 使用纯 javascript 而不影响具有相同类的其他标签?
最佳答案
您可以使用document.querySelector
,像这样:
document.querySelector('h2.some-class').innerHTML = 'string to replace';
对于多个元素:
document.querySelectorAll('h2.some-class').forEach(function(el) {
el.innerHTML = "string to replace";
});
关于javascript - 用javascript中的类替换标签的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57390585/