[英]How to wrap the specific text with span tag inside the <p> tag
var dtag = document.querySelector('p') let len = dtag.innerHTML.split(' ').length for(let i = 0; i < len; i++){ if(dtag.innerHTML.split(' ')[i] === 'Format'){ let span = document.createElement('span') span.append(dtag.innerHTML.split(' ')[i]) dtag.append(span) } }
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> <script src="commanwords1.js" defer></script> </head> <body> <p>Printable Format hello shivam</p> </body> </html>
我添加了 HTML 和脚本标记中的 javascript 代码。 请让我知道我应该怎么做才能在特定单词中添加 span 标签。
当您尝试 append 元素时,您没有处理文本节点。 由于您使用的是 innerHTML,因此您可以构建字符串并替换 innerHTML。
const dtag = document.querySelector('p') const words = dtag.innerHTML.split(' '); const mapped = words.map(word => word === 'Format'? `<span>${word}</span>`: word); dtag.innerHTML = mapped.join(' ');
p span { color: green }
<p>Printable Format hello shivam</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.