frequent
frequent

Reputation: 28513

How to conditionally chain in jQuery without specifying a shorthand else statement?

I have a list with linked or no-link items, so the HTML looks like this:

<ul>
 <li>
   <a href="#">
     <img />
     <h3>Hello</h3>
     <p>World</p>
   </a>
 </li>
 <li>
   <img />
   <h3>Foo</h3>
   <p>Bar</p>
 </li>
</ul>

I'm trying to wrap everything inside the list item (or list item link) that is not an image.

Here is what I'm doing:

// inside a loop over the listitems
var item = items[i];
var containsLinks = item.children.length === 1 && item.children[0].tagName === "A";

// this does not work...
var captionsContent = $( item ).children()
    .filter(containsLinks ? "a" : null)
    .not("img")
    .wrap( "<div class='ui-captions-content'></div>" );

// neither does that
var captionsContent = $( item ).children()[containsLinks ? children : null]()
    .not("img")
    .wrap( "<div class='ui-captions-content'></div>" );

Question:
How do I "null" the return in a shorthand if-else statement in jQuery or how do I do a conditional chaining without the shorthand else-statement?

Thanks!

Upvotes: 0

Views: 480

Answers (1)

frequent
frequent

Reputation: 28513

This worked for me:

var captionsContent = $( item )
  .find(containsLinks ? "a *" : "*")
  .not("img")
  .wrap( "<div class='foo'></div>");

Short and barring a better answer, I will live with it.

Upvotes: 1

Related Questions