如何使用javascript更改html元素的标题级别

问题描述

如果我有类似的东西:

<h2> test text </h2>

我将如何使用JavaScript来使文本现在位于段落标记内:

<p> test text </p>

我以为我可以做类似的事情:

var text = ('h2').text();

('h2').replace('<p>' + text + '</p>');

但是效果不佳。

解决方法

在普通JS中,选择元素,创建一个<p>元素,然后使用replaceWith<h2>替换为新的<p>

const h2 = document.querySelector('h2');
const p = document.createElement('p');
p.textContent = h2.textContent;
h2.replaceWith(p);

console.log(document.body.children[0].outerHTML);
<h2> test text </h2>

,

您可以使用outerHTML替换标签名称。

// document.getElementById("93").outerHTML = document.getElementById("93").outerHTML.replace(/wns/g,"lmn")

const h2List = document.getElementsByTagName('h2');
for (let index = 0; index < h2List.length; index ++) {
  h2List[index].outerHTML = h2List[index].outerHTML.replace(/h2/g,'p');
}
<h2> test text </h2>

,

像这样简单地更改@ElementCollection @Column(name = "categories") var categories: List<String>? = emptyList() 标记的outerHTML

h2
const el = document.querySelector('h2');
el.outerHTML = '<p>' + el.innerHTML + '</p>';