简体   繁体   中英

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>

I have added the HTML and In the script tag the javascript code. Please let me know what should I have do to add the span tag in the specific word.

You are not working off the text nodes when you are trying to append the element. Since you are working with innerHTML you can build the string and replace the 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM