1

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.

2
  • 1
    you are missing return from the function you pass to map() Commented Dec 22, 2012 at 22:05
  • If you're trying to compare dates, you're also missing getTime() to get the timestamp. And you're redeclearing the time variable. Commented Dec 22, 2012 at 22:09

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I believe I should sleep now.
1

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/

2 Comments

Cool, didn't knew about this.
map() likely uses filter() internally in jQuery, but what you want is the elements so this method makes most sense to me

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.