Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading