0

This will probably sound silly, but I want to optimize my jQuery code in order to achieve something like this:

jQuery("#myid).{ // Here, how can I make it work?
    var value = jQuery(this).val();
    if(value == null || value == ""){
     jQuery(this).addClass("error");
    }
    // and so on
}

Basically, I want to select a DOM element and apply various codes to it. How can I do it?

1
  • Ty guys, the idea is to add as many operations as I want - select the object once and than access it using (this) Commented May 22, 2013 at 19:20

3 Answers 3

1

Just assign it to a variable:

var $elem = jQuery("#myid");
var value = $elem.val();

if (value == null || value == ""){
    $elem.addClass("error");
}

You could also use .each(), as it'll iterate only over your single element, but it's somewhat confusing in my opinion:

jQuery("#myid").each(function(){
    var value = jQuery(this).val();
    if(value == null || value == ""){
     jQuery(this).addClass("error");
    }
    // and so on
})
Sign up to request clarification or add additional context in comments.

3 Comments

#myid and .each? I don't think it works well as jQuery would return single element when it looks a # which is going to use .getElementById.
@Vega: You can iterate over the set of matched elements. The selector still returns a jQuery object.
Ty, the idea is to add as many operations as I want - select the object once and than access it using (this) - So the assign into variable looks pretty good
1

Use the anonymous function:

jQuery("#myid").addClass(function(){   // To addClass
     return this.value ? 'error' : '';
}).css('width', function() {           // For css
     return this.value || 400;
}).attr("id", function () {            // For attribute change
     return "newID";
});

2 Comments

I don't think this.value can return null, so you can just do this.value ? 'error' : ''.
Yes, that's much better. Thanks :)
0

If you have operation more than addClass, use .each

$("#myid").each(function() {
    var value = $(this).val();
    if(value == null || value == ""){
      $(this).addClass("error");
    }
    // and so on
});

Comments

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.