<div id="main">
<span>v</span>
<div id="main_cursor"></div>
</div>
function highlight_word() {
var cursor = document.getElementById(area + '_cursor'),
pe = cursor.previousElementSibling,
ne = cursor.nextElementSibling;
var word = [];
f();
word = word.join();
if (isInArr(keywords_arr, word)) {
f(true);
};
function f(p = false) {
while ((pe === null ? " " : pe.innerHTML) !== " " ||
(ne === null ? " " : ne.innerHTML) !== " ") {
if (pe !== null) {
while (pe.innerHTML !== " ") {
p === true ? pe.style.color = "green" : word.push(pe.innerHTML);
pe = pe.previousElementSibling;
}; // end of while
word = word.reverse();
}; //end of if
if (ne !== null) {
while (ne.innerHTML !== " ") {
p === true ? pe.style.color = "green" : word.push(ne.innerHTML);
ne = ne.nextElementSibling;
}; //end of while
}; //end of if
}; // end of while
}; // end of function f
};
The objective is that first of all get the inner text of all the span which are between the main_cursor and a span with a space as inner text and check if the word obtain is present in the array keywords_arr. Is that word is present in that array then change the colour of text all those spans
or just highlight if the word is in keyword_arr
Uncaught TypeError: Cannot read property 'innerHTML' of null
error is shown in the line-
while(pe.innerHTML!==" "){
and this happens only when the condition of pe!==null get satisfied which should not happen!
what should I do?
Inside of this loop
while (pe.innerHTML !== " ") {
p === true ? pe.style.color = "green" : word.push(pe.innerHTML);
pe = pe.previousElementSibling;
}; // end of while
You're reassigning the value of pe. If pe no longer has any previous siblings, it will be assigned to null.
Instead, you could change your condition to this to ensure that pe is valid before checking it's innerHTML:
while (pe && pe.innerHTML !== " ") {