geeta battin
geeta battin

Reputation: 75

Uncaught TypeError: Cannot read property '0' of undefined

Here I have div with class box-title and I have span with related products and I want to change its text to 'Choose Extra To make It More Special' Why this error is coming please anyone can tell me.

function onloadCall()
{   
    var divs = document.getElementsByClassName('box-title');
    for(var i = 0; i < divs.length; i++)
    {
        var div = divs[i];
        if(!div) break
        var span = div.getElementsByTagName('span')[0];
        if(span[0].innerHTML == 'Related Products') 
            span[0].innerHTML='Choose Extra To make It More Special';
    }
}
window.addEventListener('load', onloadCall, false);

Actually, my HTML tag is like this:

<div class="box-title"><strong><span>Related Products<span></strong></div>

Upvotes: 1

Views: 10769

Answers (3)

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

if(!div) {
    break;
}
var span = div.getElementsByTagName('span')[0];
if(span && span.innerHTML == 'Related Products') {
    span.innerHTML = 'Choose Extra To make It More Special';
}

demo

Upvotes: 0

Charles
Charles

Reputation: 1122

var span = div.getElementsByTagName('span')[0];
if(span[0].innerHTML == 'Related Products') 
    span[0].innerHTML='Choose Extra To make It More Special';

I see you grabbing the first index of the array and then trying to grab the first index of that when it isn't an array.

Try:

var span = div.getElementsByTagName('span')[0];
if(span.innerHTML == 'Related Products') 
    span.innerHTML='Choose Extra To make It More Special';

Upvotes: 0

dinox0r
dinox0r

Reputation: 16039

Change:

if(span[0].innerHTML == 'Related Products') 
    span[0].innerHTML='Choose Extra To make It More Special';

for:

if(span.innerHTML == 'Related Products') 
    span.innerHTML='Choose Extra To make It More Special';

And it should work.

Also, you can change the following:

var span = div.getElementsByTagName('span')[0];

For:

var span = div.getElementsByTagName('span');

And leave the other code unchanged. If neither of this works, then make sure that there are any span tags in your html file.

Upvotes: 1

Related Questions