Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Error (IE): Object doesn't support this property or method

2015 Note: Everyone should go look through their old questions and be encouraged by how far they've come. There are so many things wrong with this code – it's wonderful.

This code works PERFECTLY in Firefox, and in IE the line ending 'negative'); breaks. I have no idea how to fix it! Argghhh!

$(".topline strong").digits().each(function () {
    s = $(this),
    c = "change";
    if ($(s).hasClass(c) & $(s).text().replace(/%/gi, "") > 0) {
        $(s).addClass("positive");
    }
    if ($(s).hasClass(c) & $(s).text().trim().charAt(0) == "-") $(s).addClass("negative");
});
like image 723
Phil Ricketts Avatar asked Apr 07 '26 23:04

Phil Ricketts


2 Answers

  1. Please use && instead of & (unless it's meant for minimizing)
  2. String.trim isn't widely implemented yet. Use

    $(s).hasClass(c) && /^\s*-/.test($(s).text())
    

    instead.

I'd rather rewrite the code as:

$(".topline strong").digits().each(function() {
  var s = $(this);
  if (s.hasClass("change")) { // no need to $() an already $()-ed object.
    var value = parseFloat(s.text());
    if (value != 0)
      s.addClass(value > 0 ? "positive" : "negative"); 
  }
});
like image 140
kennytm Avatar answered Apr 11 '26 04:04

kennytm


Instead of .trim() you can use $.trim() like this:

$(".topline strong").digits().each(function () {
  var s = $(this), c = "change";
  if (s.hasClass(c) && s.text().replace(/%/gi, "") > 0) { s.addClass("positive"); }
  if (s.hasClass(c) && $.trim(s.text()).charAt(0) == "-") s.addClass("negative");
});

Also note the s changes, there's no need to clone it as another jQuery object each time, it already is one so use it :) As for the error: .trim() isn't in all browsers, this is why jQuery includes the $.trim() function (same reason it has $.inArray(), IE doesn't have .indexOf()).

Also when declaring variable use var, otherwise you're creating global variables.


As an aside for future readers of this, jQuery 1.4.3+ will use the native String.prototype.trim if it's available when calling $.trim().

like image 37
Nick Craver Avatar answered Apr 11 '26 04:04

Nick Craver