Display elements one by one with . each jquery

Asked

Viewed 171 times

1

Hello, guys. I’m having problems with the . each of jQuery. I have an xml like this:

<dados>
<usuarios>
    <usuario id="1">
        <login>usuario12</login>
        <senha>21</senha>
    </usuario>
    <usuario id="2">
        <login>usuario23</login>
        <senha>23</senha>
    </usuario>
</usuarios>

and I’m trying to read it like this with jQuery:

$(xml).find("usuarios").each(function() {
        console.log($(this).find("usuario").text());
});

but the console shows me so:

user 1212user 2323

Can you help me?

  • What you hoped to receive on the console?

  • I expected to receive something like a "{login: user, password: pswd}" object, you know?

  • Okay, that’s not what the answer you marked as accepted gives you, but I imagine you were able to do the rest.

  • 1

    Actually with the answer code I was able to get the login object and the password object separately. Before I was just getting a string run with all the information

1 answer

2


You gave . find by usuarios, but you only have 1 usuarios. Try just putting usuario, that way:

var xml = '<dados><usuarios><usuario id="1"><login>usuario12</login><senha>21</senha></usuario><usuario id="2"><login>usuario23</login>        <senha>23</senha></usuario></usuarios>';

$(xml).find('usuario').each(function () {
  console.log("id:" + $(this).attr('id'));
  console.log("login:" + $(this).find('login').text());
  console.log("senha:" + $(this).find('senha').text());

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • Okay, that’s right! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.