1

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!

3 Answers 3

2

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>'
});
Sign up to request clarification or add additional context in comments.

3 Comments

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 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!
Oh, sorry - I meant that the function/inline anonymous function is set within the elementTag option array.
2

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?

1 Comment

Thanks for showing me these extra ideas, I'll be sure to remember them.
0

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.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.