Reputation: 173
I would like to know how I can give highlight on any letter and if there is a space after or before the word it doesn't eat the space...
function highlight(text) {
const InputsTexts = document.querySelectorAll('.item-question-faq');
for (const inputText of InputsTexts) {
let innerHTML = inputText.innerHTML;
let index = innerHTML.toUpperCase().indexOf(text.toUpperCase());
if (index !== -1) {
innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + '</span>' + innerHTML.substring(index + text.length);
inputText.innerHTML = innerHTML;
}
}
}
document.body.onload = function() { highlight('order'); };
.item-question-faq {
display: flex;
margin-left: 5px;
align-items: center;
font-size: 14px;
margin-left: 3px;
margin-right: 3px;
}
.highlight {
background: yellow;
}
<p class="item-question-faq webrep-faq" >the order is important</p>
Here is a printout of how it looks when applying the highlight
the application can't use Jquery or libraries how can i solve this?
Upvotes: 0
Views: 227
Reputation: 9057
This is because you've set the parent element (paragraph) to display: flex
. Part of what a flexbox does is decide how to pack in the children elements, and how much space to add between them.
It is almost certainly a mistake to use display: flex
for an element that directly contains raw text. Usually, flexboxes are wrapper elements that contain discrete blocks of content.
If you remove this property, allowing the paragraph to use its native display: block
mode, the spaces will be preserved as you expected.
function highlight(text) {
const InputsTexts = document.querySelectorAll('.item-question-faq');
for (const inputText of InputsTexts) {
let innerHTML = inputText.innerHTML;
let index = innerHTML.toUpperCase().indexOf(text.toUpperCase());
if (index !== -1) {
innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + '</span>' + innerHTML.substring(index + text.length);
inputText.innerHTML = innerHTML;
}
}
}
document.body.onload = function() { highlight('order'); };
.item-question-faq {
margin-left: 5px;
align-items: center;
font-size: 14px;
margin-left: 3px;
margin-right: 3px;
}
.highlight {
background: yellow;
}
<p class="item-question-faq webrep-faq" >the order is important</p>
minor tip: you can use javascript's forEach to make your code just a little more concise.
Instead of:
const InputsTexts = document.querySelectorAll('.item-question-faq');
for (const inputText of InputsTexts) {
/* do stuff */
}
Consider:
document.querySelectorAll('.item-question-faq').forEach((inputText) => {
/* do stuff */
});
Upvotes: 2