-1

HTML

<div id="main">
  <span>v</span>
  <div id="main_cursor"></div>
</div>

Javascript

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
};

Objective

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

Error

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?

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Sanmveg saini
  • 744
  • 1
  • 7
  • 22
  • You say it should not happen, but apparently it does. The last command in the while is `pe=pe.previousElementSibling;` and then you no longer check if it's null before continuing the loop. So once it runs out of previous siblings... – Mr Lister Mar 24 '16 at 17:05
  • are you ensuring that you're accessing only span elements? You should ensure using tagName or even document.getElementsByTagName. – Ricardo Pontual Mar 24 '16 at 17:09

1 Answers1

2

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 !== " ") {
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91