Rohit
Rohit

Reputation: 92

How to add a css on a div by finding a children class on its sibling div by jquery

i have to add position on based of its sibling div children has a class or not by jquery but it is not working. anybody can help me please.

html

 <div class="new">
   <div class="rt">
     test321
    </div>
 </div>


  <div class="new1">
    new1
  </div>
  <button> click</button>

jQuery

    $(document).ready(function(){
    $('button').click(function(){
        if($('.new').find('.tr')){
          $('.new1').css("position", "absolute");
          alert('absolute');
        }
        else{
          $('.new1').css("position", "relative");
          alert('relative');
        }
    });
});

i have used this code but don't know what is prob. in this code i want to find a class tr . if its is present on new container then new1 has position:absolute else new new1 has position relative but every time it give absolute position.

anybody can help please to figure this out.

https://jsfiddle.net/0ov8nkwj/

Upvotes: 0

Views: 48

Answers (3)

Ashish M
Ashish M

Reputation: 1

Just add .length after $('.new').find('.tr') in check condition

$('button').click(function(){
    if($('.new').find('.tr').length){
        $('.new1').css("position", "absolute");
        alert('absolute');
    }
    else{
        $('.new1').css("position", "relative");
        alert('relative');
    }
});

Upvotes: 0

void
void

Reputation: 36703

Do this

$('.new').find('.tr').length!=0 to check whether element exists or not.

Updated fiddle

Upvotes: 2

Samir
Samir

Reputation: 1368

According to your HTML,

$(document).ready(function(){
    $('button').click(function(){
        if($('.new').find('div').hasClass('rt')){
          $('.new1').css("position", "absolute");
          alert('absolute');
        }
        else{
          $('.new1').css("position", "relative");
          alert('relative');
        }
    });
});

Upvotes: 0

Related Questions