Let's say I have an HTML document with the following body
:
<style>
.highlighted {
color: red;
background-color: yellow;
}
</style>
<article>My text in an element</article>
I have the challenge to style the i
letter from the in
word inside the <article>
tag with javascript, and I'm required to do it by it's index
[8].
So far I can only think of starting with this...
<script>
const article = document.querySelector('article').innerText
console.log(article[8]);
</script>
Expected output:
<article>My text <span class="highlighted">i</span>n an element</article>
// Console
>>>> "i"
...although I've never tried anything like this before, so I'm kinda lost with the following steps.
I supose I need to insert a <span>
tag by this index, but I'm not sure how I would set the closing </span>
tag or update the DOM.
What would be a good way to achieve this kind of styling?
CodePudding user response:
//get text of article
const article = document.querySelector('article').innerText;
//find index of word 'in'
const index = article.indexOf('in');
//opening and closing tags
const openingTag = '<span style="color:red">'
const closingTag = '</span>'
//insert tags into article
const newHTML
= article.slice(0, index)
openingTag 'in' closingTag
article.slice(index 2);
document.querySelector('article').innerHTML = newHTML;
This code styles the first occurrence of the word "in" by setting the text color to red. If you want to do something else, change the style
attribute of the opening tag.
article.slice(0, index)
returns everything before the word "in." In your example, this would evaluate to 'My text '
. article.slice(index 2)
returns everything after the word "in" because "in" is 2 letters long. In your example, this would evaluated to ' an element'
. When all the strings are concatenated together, the result is 'My text <span style="color:red">in</span> an element'
.
CodePudding user response:
const HIGHLIGHT_IDX = 8;
const article = document.querySelector('article').innerText;
const words = article.split(' ');
let highlightCheck = words[0].length;
let wordToHighlight = words[0].length >= HIGHLIGHT_IDX && '0';
let wordIdx = 1;
while (!wordToHighlight) {
highlightCheck = 1 words[wordIdx].length;
if (highlightCheck >= HIGHLIGHT_IDX) {
wordToHighlight = wordIdx;
} else {
wordIdx = 1;
}
}
words[wordToHighlight] =
`<span >${words[wordToHighlight]}</span>`;
document.querySelector('article').innerText = words.join(' ');