1

I'm populating an set of <article> in HTML with either an images or a flash movie depending on the attributes set in an XML like so,

<article image="" flash="flash/1.swf"></article>// this article has flash only
<article image="image/1.jpg" flash=""></article>// this article has image only

There a "n" number of "articles" depending on the XML file. Every article has either an image or a flash movie.

After i load the XML using .ajax(), i'm using .append() to add <img> and <object> to the article. The problem is, now I have empty tags (img or object) in each article. All articles assigned with images in them have a blank <object> tag within them and vice versa.

How can I check the XML before appending? So when an article has been assigned an image, the <object> tag doesn't appear?

The jQuery is as shown below

$('#container').append('<article><img src="'+$image+'"/><object><param name="movie" value="'+$flash+'"></object></article>');
pixeltocode
  • 5,312
  • 11
  • 52
  • 69
  • I think the accepted answer here is a better solution : [jQuery hasAttr checking to see if there is an attribute on an element [duplicate]](http://stackoverflow.com/questions/1318076/jquery-hasattr-checking-to-see-if-there-is-an-attribute-on-an-element) – Fabii Oct 08 '15 at 16:19

3 Answers3

1

You should first check if the attribute exists before assigning it to a variable.

if($(this).attr('flash');){

    // this attribute exists 
    // you can also check if its null or not

} else {

    // this attribute does NOT exist
}
1

This worked for me

var $flash = $(this).attr('flash');
if ($flash == null) {
...
}
else {
...
}
pixeltocode
  • 5,312
  • 11
  • 52
  • 69
0

If order is not important to you you should first filter for the flash attributes, and than for the image attributes. Otherwise something like:

.append('<article>' + ($image != null) ? <img.. : <object..) + "</article>";
dr jerry
  • 9,768
  • 24
  • 79
  • 122