ronnie
ronnie

Reputation: 1839

Javascript: return html element from a function

I am trying to filter certain html element using the datetime attributes. My html elements looks like

<time title="Sat Dec 22 16:29:21 2012 UTC" datetime="2012-12-22T16:29:21+00:00">4 hours</time>

Now, what I am doing is

var x = $("p time").map(function() { filter(this);})

and my filter function looks like:

function filter(var1){

  var now = new Date();
  var time = $(var1).attr("datetime");

  var time = new Date(time);
  var diff = now - time;

  if( diff < 7200000){

   console.log("yes");
   return $(var1).parent().parent();

  }
}

When I run the above code I get x as an empty array and yes is printed 9 times.

So, my question is why my filter function is not returning the parent html tag.

Upvotes: 1

Views: 3621

Answers (2)

charlietfl
charlietfl

Reputation: 171679

Use jQuery filter() method

var p_parents_I_want = $("p time").filter(function() {
    var now = new Date();
    var time = $(this).attr("datetime");
    time = new Date(time);/* don't declare same var twice*/
    var diff = now - time;

    return diff < 7200000

}).parent().parent()

Can usually replace parent().parent() using closest(selector)

API reference: http://api.jquery.com/filter/

Upvotes: 1

David G
David G

Reputation: 96790

var x = $("p time").map(function() { filter(this); });

Should be

var x = $("p time").map(function() { return filter(this); });

You're missing the return statement.

Upvotes: 2

Related Questions