Home > Mobile >  How to wrap the specific text with span tag inside the <p> tag
How to wrap the specific text with span tag inside the <p> tag

Time:10-04

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.

CodePudding user response:

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>

  • Related