Gergely Kudó
Gergely Kudó

Reputation: 69

Cannot read property 'index Of' of undefined in HTML and Javascript

I try to highlight on my page the search expression with a button. Can anyone help me please to solve this problem?

Uncaught TypeError: Cannot read property 'indexOf' of undefined at highlight (?q=Python:11) at HTMLButtonElement.onclick (?q=Python:24)

The JS code:

function highlight(text) {
        var titles = document.getElementsByClassName('title');
        for (var x in titles) {
            var innerHTML = titles[x].innerHTML;
            var index = innerHTML.indexOf(text);
            if (index >= 0) {
                innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + "</span>" + innerHTML.substring(index + text.length);
                x.innerHTML = innerHTML;
            }
        }
    }

Line 11:

var index = innerHTML.indexOf(text);

Line 24:

<button onclick="highlight('{{ search_expression }}')">Highlight search expression</button>

Upvotes: 0

Views: 157

Answers (2)

NineBerry
NineBerry

Reputation: 28499

Don't use for .. in to iterate over the list of elements, but a traditional for loop.

function highlight(text) 
{
        var titles = document.getElementsByClassName('title');
        for (var i=0; i < titles.length; i++) 
        {
            var title = titles[i];
            var innerHTML = title.innerHTML;

            // Work with title some more.
        }
}

For an explanation what is happening see Why is using "for...in" with array iteration a bad idea?

Upvotes: 2

lipp
lipp

Reputation: 5936

innerHTML might be undefined. You have to check if innerHTML is defined before calling innerHTML.indexOf

var innerHTML = titles[x].innerHTML
if (innerHTML) {
  var index = innerHTML.indexOf(text)
  ...
}

Upvotes: 0

Related Questions