-1

Using .length to check if div with class exist and if exist .append should not add a new div.

https://jsfiddle.net/uhvL1hfx/

HTML

<div class="container">
  <div class="inner">
    <div class="field">
    This div exist, so .append should not add a new div, should add only if this div does not exist.
    </div>
  </div>
</div>

jQuery

if( $("div.container div.inner div.field").length ){
    $("div.container div.inner").append("<div>But for some reason it still adds it.</div>");
}

But it still appends a new div. Should append if div.field does not exist.

j08691
  • 204,283
  • 31
  • 260
  • 272
user3108268
  • 1,043
  • 3
  • 18
  • 37
  • 4
    A simple `!` before your selector should do you some good. – Wild Beard Jan 11 '18 at 22:40
  • Suggested post for jQuery selector: https://stackoverflow.com/questions/3767512/jquery-class-within-class-selector. Also as Wild Beard has noted, I believe using (!$('selector')) instead of .length would be preferred. [edit: I stand corrected, that .length is still necessary] – Kyle B. Jan 11 '18 at 22:42
  • @KyleBallard You still need `.length`. A selector is always truthy. – Barmar Jan 11 '18 at 22:45
  • 1
    @KyleBallard Wild Beard isn't suggesting to use `!` *instead* of using `.length`, he's suggesting using it *in addition* to it. – j08691 Jan 11 '18 at 22:45

2 Answers2

1

Your condition should be $("div.container div.inner div.field").length == 0 to check if there is no other element with the class in the container div before appending it.

if( $("div.container div.inner div.field").length == 0){
    $("div.container div.inner").append("<div class=\"field\">But for some reason it still adds it.</div>");
}

I also gave the class of field to the div you are appending so that the next time the code is executing it the condition will fail since there is now a div with the given class present in the container div.

Kevin B
  • 94,570
  • 16
  • 163
  • 180
Kamga Simo Junior
  • 1,679
  • 2
  • 16
  • 30
  • Does this work only for one element on the page or for multiple? I got this working on jsfiddle, but can't reproduce on actual website. – user3108268 Jan 11 '18 at 22:55
  • The condition here is checking if a div of class field exist in the container div. if you want to use multiple element you will need to check with their `ids` and not with a common class – Kamga Simo Junior Jan 11 '18 at 22:59
0

Because your code already has the div.field so length === 1 what you want is like this:

if( $("div.container div.inner div.field").length > 0){


}else{
    $("div.container div.inner").append("<div class=\"field\">But for some reason it still adds it.</div>");
}
Big Yang
  • 46
  • 4