views:

69

answers:

3

Hello,

I'm using a jQuery plugin named "jParse" to parse an XML file like so:

$('#content').jParse({
 ajaxOpts: {url: 'data.xml'},
 elementTag: ['title', 'description'],
 output: '<h2>jpet0</h2><p>jpet1</p>'
});

As you can see, the "jpet" variables correlate with the elementTag array.

How would I check to see if the jpet var contains data (as some of the tags in the XML are empty) and withhold the HTML tags if it doesn't?

This doesn't work:

$('#content').jParse({
 ajaxOpts: {url: 'data.xml'},
 elementTag: ['title', 'description', 'extra'],
 output: if (jpet0) { '<h2>jpet0</h2>' } + '<p>jpet1</p><p>jpet2</p>'
});

But it does give a good idea of what I'm trying to achieve.

Thanks in advance!

+1  A: 

You could use the ternary operator:

 output: (jpet0 ? '<h2>jpet0</h2>' : '') + '<p>jpet1</p><p>jpet2</p>'

But what's wrong with just putting the HTML string in a variable and then prepending the additional HTML using a regular if statement?

Ignas R
Thanks for showing me these extra ideas, I'll be sure to remember them.
James James
+2  A: 

This should work, if I understood the docs correctly:

$('#content').jParse({
   ajaxOpts: {url: 'data.xml'},
   elementTag: [
     {elem:'title', format: function(title){
        if(title != '') return '<h2>' + title + '</h2>';
        else return '';
     }}, 'description'],
   output: 'jpet0<p>jpet1</p>'
});
Doug Neiner
Thanks for this, I must've overlooked it in the docs. Although you attach the formatting to the elementTag like this:elementTag:[{elem:'title',format:formatTitle}]
James James
@James James if it accepts a function reference, it will also accept an inline anonymous function. The docs did not specify that, but it is just how JavaScript works. Glad I could help!
Doug Neiner
Oh, sorry - I meant that the function/inline anonymous function is set within the elementTag option array.
James James
Ah, does it look correct now?
Doug Neiner
Yup, wonderful.
James James
A: 

It seems jParse doesn't support that kind of template (judged from usage page; may be wrong). One possible solution then would be post-process the result, like this:

$('#content').remove('h2:empty');
// i.e. removes all empty H2 elements from #content.

Of course you have to ensure that there is no other places empty H2 elements appear.

Kang Seonghoon
The `format` option (the second last option on the usage page as of writing) looks very much like what @James James is after.
Steve Harrison
Yup, it was indeed the format option I was after, although I didn't know jQuery could do this! Thanks for the info.
James James