简体   繁体   English

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

[英]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.

相关问题 如何使用 javascript 在页面开头或图像标签之前将标题元素添加到 html 文档中 - How to add a heading element into a html document at the start of the page or before the image tags using javascript 如何使用JavaScript更改HTML元素值? - How to change HTML element value using javascript? 如何使用javascript按类名更改html元素的值 - how to change value of html element by classname using javascript 我应该如何使用javascript更改带有变量的注入HTML元素? - How should I change an injected HTML element with variable using javascript? 如何使用javascript更改html元素的图像源 - How to change image source of html element using javascript 如何使用Javascript更改没有ID的HTML元素? - How to change HTML element without ID using Javascript? 如何使用 javascript 更改 HTML 元素的边框颜色 - How to change the border colour of an HTML element using javascript 如何使用javascript更改导航元素内多级手风琴菜单子菜单的背景颜色 - How to change background color of submenu of multi level accordion menu inside a nav element by using the javascript 使用javascript更改html中的标签foreach元素 - change label foreach element in html using javascript 使用 javascript 按类名更改 html 元素的值 - Change value of html element by classname using javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM