JQuery xml each fires without element

302
June 10, 2017, at 7:32 PM

I'm facing this strange JQuery behaviour. Given an xml string with a list of ids which is empty, the each loop fires nevertheless:

var xmltext = '<xml><ids></ids></xml>';
var xmlDoc = $.parseXML(xmltext);
var xml = $(xmlDoc);
traverse(xml);
function traverse(xml) {
    if (xml != null) {
        $('ids', xml).each(function (index) {
            // why do I get here??
            var id = $('id', this).first().text();  // id is ""!
            doSomething(id);
        });
    }
}

Am I missing something obvious?

Answer 1

You seem to be assuming that the callback should fire only for non-empty id tags.

This is not the case; the jQuery selector selects the id tags. You make no stipulation of their needing to be non-empty. If that's what you mean, then:

$('ids:not(:empty)', xml).each(...
Answer 2

You are checking if xml is null , however the presence of ids does not make it so , working code

fiddle : https://jsfiddle.net/3ksvy65p/

var xmlDoc = $.parseXML(xmltext);
var xml = $(xmlDoc);
traverse(xml);
function traverse(xml) {
    if ($('ids').length != 0) {
        $('ids', xml).each(function (index) {
        alert();
            // why do I get here??
            var id = $('id', this).first().text();  // id is ""!
            doSomething(id);
        });
    }
}
Rent Charter Buses Company
READ ALSO
geting keyword from facebook comment using facebook graph

geting keyword from facebook comment using facebook graph

am thinking of do facebook live stream game , where i ask questions and people comment and i get the answers from the comment

316
Add class to direct descendent ul element

Add class to direct descendent ul element

I need to add a class to only the first ulnavigation__nav__submenu and not the second level ul

241
How to get an unique ID nested inside of the element?

How to get an unique ID nested inside of the element?

I have some <tr> elements with unique IDs

310
Make half circle with content

Make half circle with content

I just wanted to make like this imagei have a word press site

342