Question

I have a form. The structure looks like this:

<p class="elementWrap">
  <label>Name</label>
  <input class="form_elem" type="text" name="form_name">
</p>

But sometimes the structure looks like this:

<p class="elementWrap">
  <label>Phone</label>
  <input class="form_elem" type="text" name="form_phone">
  <span class="form_required">*</span>
</p>

So there is an additional span in it. Now I want to give the labels, which have a span next to them some styles with jQuery.

My code so far:

jQuery('.elementWrap').each(function() {
  if(jQuery('span.form_required').parents(this).length == 1) {
    jQuery(this).find('label').css({'width':'auto','margin':'0px'});
  }
});

But this doesn't seem to work...(I tried a lot of if statements but none worked so far =/

Was it helpful?

Solution

You could use .filter and .children to select all .elementWrap objects which have a direct .form_required child - then find the labels within that subset:

$(".elementWrap").filter(function() {
    return $(this).children(".form_required").length;
}).find("label").css({'width':'auto','margin':'0px'});

jsFiddle

There is almost always a way to avoid having to use .each and a lot of if statements.

OTHER TIPS

You could use :has() pseudo selector, e.g:

$('.elementWrap:has(.form_required)').find('label').css({'width':'auto','margin':'0px'});

DEMO

Try:

$('.elementWrap').each(function () {
    if ($(this).find('span.form_required').length != 0) {
        $(this).find('label').css({
            'width': 'auto',
            'margin': '0px'
        });
    }
});

DEMO

do like this:

$('p.elementWrap').each(function(){

if($(this).find('span.form_required').length > 0)
{
    $(this).find('label').css('background','red');
    // do whatever needed
}

})

Here is Fiddle DEMO

Try this:

jQuery('.elementWrap').has('.form_required').find('label').css({'width':'auto','margin':'0px'});

I made a JSFiddle for you: Click for the fiddle

Explanation: First i select every element with an elementWrap class (no need to do an each) But I only select those, which HAS a child with a form_required class with the .has() method. From those elementWrap elements i want to find the label and apply some custom style!

Hope this helped you out!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top