Mojo Jojo
Mojo Jojo

Reputation: 21

If div with ID A has class B, add a class X to div with ID Y

i'm really new to this so bear with me

I have this:

<div id="A" class="B"></div>
<div id="Y"></div>

I need this:

if div #A has class .B, add class .Z to div #Y

I realise it's a basic script but i can't figure it out. Please help :)

Thank you

Upvotes: 0

Views: 178

Answers (3)

Bharat
Bharat

Reputation: 2464

You can use hasClass() to check class is exists on element and then use addClass() to add class.

$(document).ready(function(){
	if($("#A").hasClass("B"))
        {
  	   $("#Y").addClass("Z")
        }
        console.log($("#Y").attr("class"))
});
<div id="A" class="B">A</div>
<div id="Y">Y<Y/div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

Upvotes: 0

Aravind Pillai
Aravind Pillai

Reputation: 771

<script>

    if ( $("#A").hasClass("B") ){
      $("#Y").addClass("Z") 
    }

</script>

Upvotes: 1

bash0ne
bash0ne

Reputation: 424

It is pretty simple if you take a look at the jquery docs. As you described it correctly:

if($('#A').hasClass('B')) {
  $('#Y').addClass('Z')
}

jQuery's hasClass doc
and
jQuery's addClass doc

Upvotes: 0

Related Questions