Wednesday, October 16, 2013

jQuery One-Liners: Part 1

I just ran into a problem today, and needed to solve it using only one line of code. I figured others of you out there have been, will be, or are currently in the same boat as I just was a matter of minutes ago. So, I'm going to share the results of my labor.

The Problem:
I needed to get all of the items on a page with a matching selector and create a pipe delimited string containing data from each of the matched elements.

EXAMPLE
<!-- SAMPLE ELEMENTS -->
<div id="someData0">DATA 0</div>
<div id="someData1">DATA 1</div>
<div id="someData2">DATA 2</div>
<div id="someData3">DATA 3</div>

<!-- DESIRED STRING -->
DATA 0|DATA 1|DATA 2|DATA 3

METHODS USED:

  1. $('selector') - jQuery selector method... read more
  2. .map() - jQuery array mapping method... read more
  3. .join() - standard js join method... read more

The Solution:
Now using the above mentioned methods we can easily achieve the desired result in one line!

JS
var merged_text = $('div[id^="someData"]').map(function(){return $(this).text();}).join('|');

I hope you found this short post helpful. You can definitely look forward to some more cool one-liners soon!

No comments:

Post a Comment

Have a question? Something to add to the post? Do it here...