ilhnctn
ilhnctn

Reputation: 2210

Uncaught TypeError: Cannot read property 'children' of undefined

I need to get href property of all a elements under a all divs of specified class. There is no problem when i hande just one div but when the number of divs increase i get the error on the title of question.. here is my demo, please take a look and dont forget to inspect the element in order to get the error message(when you click the line saying Please Click Here to take the result an alert wil peomt and simultaneously a js error will go to console)

Upvotes: 1

Views: 4674

Answers (3)

Chris
Chris

Reputation: 27627

The problem I think is more obvious if you use better named variables...

http://jsfiddle.net/hth9Z/4/

$(".pg-header").each(function(index,element) {

    for(i=0;i<$(element)[index].children.length;i++)
    {

    if($(element)[index].children[i].localName=="a")
    {
        alert($($(element)[index].children[i]).attr("href"));
        my_arr.push($($(element)[index].children[i]).attr("href"))
    }

    }

});

The parameters being passed to your function are an index and the specific item in the loop. What you are doing is taking the one element you are being passed (the current one in the loop) and wrapping it into a jquery object. You are then applying the index to that. One object being wrapped in a jquery object will still just be one item so an index of greater than one is never appropriate. Thus on your second loop when you have element as your second matched item and index is 1 then $(element)[index] is undefined and so you get the error when you call methods on it.

As it is you are better off just doing more of this with jQuery. Something like $(".pg-header a") will get all the anchor elements inside the .pg-header which you can then analyze as others have suggested.

So in summary make sure you understand what your parameters are - giving them sensible names will help with this.

See also http://api.jquery.com/each/ for information on the method you are using.

Upvotes: 1

RohitWagh
RohitWagh

Reputation: 2097

altered your code

$(".pg-header a").each(function(index,elem) {

                console.log(elem);

            });

check this one: http://jsfiddle.net/3tyzd/1/

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

If the selector is modified to .pg-header a the map() function can be used to retreive all hrefs:

function get_sub_elements(){
    var hrefs = $(".pg-header a").map(function(i,e){
       return $(e).attr("href");
    });
    for(var i = 0; i < hrefs.length; i++){
       alert(hrefs[i]);
    }
}

JS Fiddle: http://jsfiddle.net/hth9Z/3/

Upvotes: 1

Related Questions