简体   繁体   中英

If else statement for jquery using selectors to see if a certain div has been appended to it

Would this work if you had a div and you append one of these div to ? Such as

<div class ="append">
  <div id ="one"></div>
  <div id ="two"></div>
</div>

Then in jQuery do something like:

if ($(.append#one)) {do this}
else if ($(.append#two)){do this} 

each of the div #one and #two have different numbers and that matters. So I was wondering if you could somehow do an if statement to check if a div has a another div with an id appended in it, if so you do the code else if its another div with another id do code.

Edit: The divs with the id one and two are not appended to div with class append at first, i have to pick either one or two to get appended to the div append. So can i check if the div .append has either div#one appended to it, if so do this, else if div#two appended to it do this

check if a div has a another div with an id appended in it

You can use:

if ($(".append>[id]").length > 0)

or

if ($("div>div[id]").length > 0)

which will check return all items that are direct descendants of .append and have attribute id .

You can do it like following.

if ($('.append #one').length) {
   // do this
}
else if ($('.append #two').length) {
   // do this
} 

You could check if a div has a particular parent as well

if($( "#one" ).hasClass( "append" )){
  //do something
}else if($( "#two" ).hasClass( "append" )){
  //do something
}

 $(()=>{ $('#div-one').click(()=>{ $('#one').appendTo($('.append')); }); $('#check').click(()=>{ if($('.append').children('#one').length!=0){ alert('one'); } else{ alert('two'); } }); }); 
 .append{color:Red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class = "append">append</div> <div id ="one">one</div> <div id ="two">two</div> <br/> <input type='button' id='div-one' value ='append one'/> <input type='button' id='check' value='check'/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM