Andrew
Andrew

Reputation: 705

Highlight text by giving it the words you want it to highlight

Trying to pass in words and create an <a> tag and set the attribute style to yellow, basically highlight the text. I'm getting an error on the words.appendChild(newNode); Does anyone know how I could create an <a> tag with a style on the set words?

highlightText(words) {
  // words contains 4 different words.
  const newNode = document.createElement('a');
     newNode.setAttribute(
       'style',
       'background-color: yellow; display: inline;'
     );
     words.appendChild(newNode);
     // words.surroundContents(newNode);
}

In the past, this is what I have done but this is using the window.getSelection().

 highlightSelection() {
      this.complexWordIdentification(this.postIWant, this.theHardWords);
      const userSelection = window.getSelection();
      if (userSelection.toString() === null) {
         return;
      } else {
        for (let i = 0; i < userSelection.rangeCount; i++) {
            this.highlightRange(userSelection.getRangeAt(i));
            this.word = userSelection.toString();
        }
      }
    }


    highlightRange(range) {
        const newNode = document.createElement('a');
        newNode.setAttribute(
           'style',
           'background-color: yellow; display: inline;'
        ),
        range.surroundContents(newNode);
    }

I want to be able to do the same as the function highlightSelection() but instead feed in the values that I want instead of highlighting it manually.

Any advice would be appreciated!

Upvotes: 0

Views: 100

Answers (2)

omkar keluskar
omkar keluskar

Reputation: 141

You can try this approach:

I have declared the constants for simplicity. You can bring in the words through Network API calls too and pass the words to highlight method.

const words = ['Lorem', 'ipsum'];

const getWords = async () => {
	//Use API calls here or simply define pass in Constants
  highlight(words);
}

const highlight = (words) => {
	const high = document.getElementById('highlight')
  const paragraph = high.innerHTML.split(' ');
  let res = [];
  
  paragraph.map(word => {
    let t = word
    if(words.indexOf(word) > -1){ 
      t = '<a class="high">' + word + '</a>'
    }
    res.push(t)
  })
  high.innerHTML = res.join(' ')
}

window.onload = getWords();
.high{
  background-color: yellow; 
  display: inline;
  margin-right: 5px;
}
<div >
  <p id="highlight">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio odio voluptas tempora voluptates expedita quo, nemo sint ipsa similique aliquid doloribus accusamus commodi amet id adipisci eos, inventore in consectetur.
  </p>
</div>

Upvotes: 2

sjahan
sjahan

Reputation: 5960

Here is a small sample :) You just pass to the function the root element it has to inspect, and then, it's just a basic replace function!

const words = ['once', 'you'];

const highlight = (root, words) => {
  words.forEach(word => {
    root.innerHTML = root.innerHTML.replace(word, word => `<a class="highlighted">${word}</a>`);
  });
};

highlight(document.querySelector('.root'), words);
.highlighted {
  background-color: yellow;
}
<div class="root">
  <p>Let's do a simple test for once.</p>
  <p>Do you like tests?</p>
</div>

Upvotes: 1

Related Questions