Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What am I missing? (jQuery DOM traversal)

Status
Not open for further replies.

Geates

Programmer
Aug 25, 2009
1,566
US
I'm trying to traverse a DOM object. Furthermore, this DOM object is the result of $.parseHTML(). My code makes sense but it's not working so I must not be considering something. Any help would be greatly appreciated?

Code:
var str = "<div id='one'><div id='header'><b>hello</b></div><img src='a.gif'></div>";

var strElements = "";
var objDOM = $.parseHTML(str);

function traverseDOM(objDOM) {
    $.each(objDOM, function (i, element) {
        if (element.children().length > 0)
            strElements += traverseDOM(element);
        else
            strElements += 'index: ' + i + ' - ' + 'node: ' + element.nodeName + '<br>';
    });

    return strElements;
}

alert(traverseDOM(objDOM));

-Geates

 
If I run your code, I get an error.

Code:
Error: TypeError: element.children is not a function

That is children is a property, and so does not require parenthesis.


I suggest checking the error console. Firefox has a pretty good ne, and it will tell you if your JS has any issues.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
I was not representing (selecting) the elements correctly

Code:
var str = "<div id='one'><div id='header'><b id='bold'>hello</b></div><img id='image' src='a.gif'></div>";
var objDOM = $.parseHTML(str);

var strElements = "";

function traverseDOM(obj) {
    $.each(obj, function (i, element) {
        strElements += 'node: ' + element.nodeName + ' ' + element.id + '\n';    
        if ($(element).children().length > 0) {
            strElements = traverseDOM($(element).children());
        }
    });

    return strElements;
}

alert(traverseDOM(objDOM));

-Geates

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top