Home > Software design >  Setting a background color "yellow" for words in a paragraph using JavaScript
Setting a background color "yellow" for words in a paragraph using JavaScript

Time:02-18

Setting a background color "yellow" for words in a paragraph that has more than 8 characters.

I tried the below JavaScript code but it shows Cannot set properties of undefined (setting 'color')

const a=document.querySelector("p");
a.innerHTML=
a.innerText.split(" ")
.map(
   function(word){
    
    if (word.length>8){
   word.style.color="yellow";
    }
else{
  return word;
}
  }
)

.join(" ");
<h1>Heading</h1>

<!-- this is the paragraph I used-->

<p>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe?

Close up formation. You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there... I just lost my starboard engine. Get set to make your attack run.

The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all right. Inform Lord Vader we have a prisoner.

What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed, so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel.

Run, Luke! Run!</p>

CodePudding user response:

May be we can try with just having innerHTML modified with returning span elements.

<script>
    const a=document.querySelector("p");
            const text = a.innerHTML.split(" ").map(function(word) {
                if(word.length > 8) {
                    return `<span style="color: yellow;">${word}</span>`
                } else {
                    return `<span>${word}</span>`
                }
            }).join(" ")
a.innerHTML= text
</script>

CodePudding user response:

const a=document.querySelector("p");
const words=a.innerHTML.split(" ");
a.innerHTML=words.map((item)=>{
  if(item.length>8) {
    return `<span style="background:yellow">${item}</span>`
  } else {
    return item;
  }
}).join(" ");

CodePudding user response:

Simple one(highlight all word)

var wordList = document.getElementById('para').innerText.split(" ");

for (let n = 0; n < wordList.length; n  ) {
    wordList[n] = `<span >${wordList[n]}</span>`//set class for words,and make it a span
}
document.getElementById('para').innerHTML=wordList.join(" ");//set back
.word {
  background-color: yellow;
}
<h1>Heading</h1>
<p id='para'>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe?

Close up formation. You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there... I just lost my starboard engine. Get set to make your attack run.

The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all right. Inform Lord Vader we have a prisoner.

What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed, so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel.

Run, Luke! Run!</p>

Complex (highlight specific word with specific style)

const SpecialWords = [
  "It's",
  "you"//style word
];
const WordColors = [
  "word",
  "word2"//style class name
];


var wordList = document.getElementById('para').innerText.split(" ");

for (let n = 0; n < SpecialWords.length; n  ) {
    var res = replaceAll(wordList,SpecialWords[n],`<span >${SpecialWords[n]}</span>`).join(" ");//style adding
}
document.getElementById('para').innerHTML=res;//set back
function replaceAll(array, find, replace) {
var arr = array;
for (let i = 0; i < arr.length; i  ) {
    if (arr[i] == find)
        arr[i] = replace;
}
  return (arr);
}
.word {
  background-color: yellow;
}
.word2 {
  background-color: lightgreen;
}
<h1>Heading</h1>
<p id='para'>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe?

Close up formation. You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there... I just lost my starboard engine. Get set to make your attack run.

The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all right. Inform Lord Vader we have a prisoner.

What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed, so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel.

Run, Luke! Run!</p>

we have to use spans(javascript will make words to spans)

see my answer here for reference

CodePudding user response:

For this you have to create span elements because you need to add background color on each word. Here is a snippet that inserts appends span tag if the the word has more than 8 characters. If the words have less than 8, it will be inserted as a text.

const a=document.querySelector("p");
const b = document.createElement("span");
b.style.background = "yellow";
const words = a.innerHTML.split(" ");
a.innerHTML = "";
for(let i=0; i<words.length;i  ){
  if(words[i].length>8){
    b.innerText = words[i];
    b.innerText  = " ";
    a.appendChild(b);
    }
    else{
      a.innerHTML  = words[i];
      a.innerHTML  = " ";
    }
}
<h1>Heading</h1>

<!-- this is the paragraph I used-->

<p>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe?

Close up formation. You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there... I just lost my starboard engine. Get set to make your attack run.

The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all right. Inform Lord Vader we have a prisoner.

What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed, so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel.

Run, Luke! Run!</p>

CodePudding user response:

filter function is Appropriate for your issue:

const element = document.querySelector("p");
const array = element.innerText.split(" ");
const eightCharacter = array.filter(function(word) {
  return word.length > 8;
});

const filteredWord = array.map(function(word) {
  if (eightCharacter.indexOf(word) != -1) {
    return '<span >'   word   '</span>';
  } else {
    return word;
  }
});

element.innerHTML = filteredWord.join(' ');
.word {
  color: yellow;
}
<h1>Heading</h1>

<!-- this is the paragraph I used-->

<p>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm
  not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe? Close up formation.
  You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there...
  I just lost my starboard engine. Get set to make your attack run. The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is
  a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all
  right. Inform Lord Vader we have a prisoner. What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed,
  so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel. Run, Luke! Run!</p>

Note to: Using arrays to change color of certain words in an input box

  • Related