PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to wrap the specific text with span tag inside the <p> tag

 October 15, 2022     dom, html, javascript     No comments   

Issue

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

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>



Answered By - epascarello
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing