[英]how to change the heading level of an html element using javascript
If I have something like:如果我有类似的东西:
<h2> test text </h2>
How would I use JavaScript to make it so that the text is now within a paragraph tag:我将如何使用 JavaScript 使文本现在位于段落标记中:
<p> test text </p>
I was thinking I could do something like:我在想我可以做这样的事情:
var text = ('h2').text();
('h2').replace('<p>' + text + '</p>');
But it did not quite work.但它并没有完全奏效。
In vanilla JS, select the element, create a <p>
element, and use replaceWith
to replace the <h2>
with the new <p>
:在 vanilla 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>
You can use outerHTML to replace the tag name.您可以使用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>
Simply change the outerHTML
of the h2
tag like this:只需像这样更改h2
标签的outerHTML
:
const el = document.querySelector('h2'); el.outerHTML = '<p>' + el.innerHTML + '</p>';
<h2>Test 01</h2>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.