質問

I've ran into a small snag with my code - below is my code:

var actionsAllowed = $(packet).find('actionsAllowed');

This returns to me the following in the firebug console:

Object[actionsAllowed]

Clicking "actionsAllowed" takes me into the packet and to the correct section, where I see the two listed actions.

I can expand the object and eventually see the following:

Object[actions]

0
    actions

remove
    remove()

attributes
    []

baseURI
    "http://localhost:9000/testget#"

childElementCount
    2

childNodes
    NodeList[ActionOne, ActionTwo]

0
    ActionOne

1
    ActionTwo

length
    2

item
    item()

iterator
    iterator()

__proto__
    NodeListPrototype { item=item(), iterator=iterator()}

So under the NodeList I see the correct actions.

The issue I am having is that I don't know how to get those actions out of there and listed or even just have them available as separate variables.

My attempt at getting then logging each child:

function getActionsAllowed() {
    var children = actionsAllowed.childNodes;
        for (var i = 0; i < children.length; i++) {
            console.log(children);
        }
}

Problem is, ".childNodes" keeps returning as "undefined".

Is there another, better way to do this? Or is this correct but I've made a mistake?

Thank you.

Kind Regards,

Gary Shergill

EDIT:

working code for just one result:

var currentState = $(packet).find('currentState').text();
var actionsBanned = $(packet).find('actionsBanned').text();

EDIT 2:

Updated code to:

$(packet).find('actionsAllowed').each(function () {
    var children = this.childNodes;
        for (var i = 0; i < children.length; i++) {
        var action = children[i].nodeName
            console.log(action);
        }
});

This works =) It logs each action one by one, so it's working. Just a matter of choosing how to change the console.log() to something more useful (need to define each one seperately...).

Will create a new thread if I have trouble and link it from here.

(my related thread: Returning Arrays and ChildNodes)

役に立ちましたか?

解決

You can always extract the DOM nodes from the jQuery object using toArray or get.

var actionsAllowed = $(packet).find('actionsAllowed').get();

But that's generally not necessary since the jQuery object itself implements an extensive API to manipulate the nodes.

E.g. looping over the nodes

$(packet).find('actionsAllowed').each(function () {
    //looping over childnodes
    $(this).children().each(function () {
        console.log($(this).text());
    });
});

If you just want to children of actionsAllowed nodes directly, you can also do:

$(packet).find('actionsAllowed > *').each(function () {
    console.log($(this).text());
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top