tags:

views:

130

answers:

4

Hey Guys,

I am pretty new to Javascript and jQuery and getting a little confused with "Selectors". Now I am sure you are all gurus and will find this trivial, so hoping you can help.

I have this HTML:

  <div class="class0">
    <div class="class1">
      <div class="class2">
        <div class="class3">Field 1:</div>
           <label class="class4">
               <input name="field" type="text" class="class5" />
           </label>

I am trying to addClasses to a number of elements but am getting stuck. I am trying to:

jQuery('.class0 input')
    .focus(function() {
    jQuery(this).parents('.class1').addClass("special_class");
    jQuery(this).parents('.class3').addClass("special_class_1");
    jQuery(this).parents('.class5').addClass("special_class_2");

But it doesn't seem to work - Class 1 does but the rest dont ? If anyone can help out would really appreciate it!

Thanks

A: 

If you are targeting one parent only then use .closest rather than parents.

Also if you know the node type of an element with a class it is always better to prefix the selector. In this case they all look like divs.

Try:

jQuery('div.class0 input').focus(function() {

    var $el= $(this);
    $el.closest('div.class1').addClass("special_class");
    $el.closest('div.class3').addClass("special_class_1");
    $el.closest('div.class5').addClass("special_class_2");

});
redsquare
legend thanks! works like a charm!
Good stuff:)
redsquare
A: 

I suspect that should be:

jQuery('.class1').parents().addClass("special_class");
jQuery('.class3').parents().addClass("special_class_1");
jQuery('.class5').parents().addClass("special_class_2");

or even like this:

$('.class1').parents().addClass("special_class");
$('.class3').parents().addClass("special_class_1");
$('.class5').parents().addClass("special_class_2");

since $ variable is set to jQuery upon its initialization.

maksymko
thanks a lot the use of "closest" worked!
A: 

If you want to add 'new_class' to div with 'old_class' you should do something like this:

$('div.old_class').addClass('new_class');

If you want to add 'new_class' to parent of div with 'old_class' you should do something like this:

$('div.old_class').parent().addClass('new_class')
ppiotrowicz
A: 

I know the solution to change the class on those divs has been found but I think it needs to be pointed out that in your example above, the following is true:

  1. input with class="class5" is the 'this' object, and not a parent so the selector when using parent('.class5') will not find it

  2. In the hierarchy, the div with class="class3" gets closed and so is not a parent of 'input.class5'. Rather, the div with class="class3" is a sibling of the label in your example.

So the following would have worked:

jQuery(this).parents('.class2').addClass("special_class_1");

Keep in mind the tree-like structure if you're going to use parent() or similar

David Archer