2

I have the following code:

<html>
    <head>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    </head>
<body>
    <span></span>

    <div class="content" id="2">
    <div class="reply"></div>
    </div>

    <div class="content" id="1">
    </div>

    <div class="content" id="3">
        <div class"reply"></div>
    </div>

        <script>
        var n = $( ".reply" ).length; 
        $( "span" ).text( "There are " + n + " divs.");
    </script>
</body>

</html>

I am trying to write a jQuery script that will check individual divs with unique id's to see if it contains the "reply" div. I have code to see if the "reply" div exists at all working. I am new to jQuery so I am unsure how to go about this.

var n = $( ".reply" ).length; 
        $( "span" ).text( "There are " + n + " divs.");
Yamaha32088
  • 4,125
  • 9
  • 46
  • 97
  • 1
    What's wrong with what you have? Seems fine http://jsfiddle.net/j08691/SdRYd/1/ (although you forgot the `=` in `
    – j08691 Oct 06 '13 at 18:39
  • Your approach is totally fine. See also [Is there an "exists" function for jQuery?](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – Bergi Oct 06 '13 at 18:43

3 Answers3

3

Use #uniqueId .reply jQuery selector:

alert("The id with id '3' contains" + $("#3 .reply").length + ".reply divs.");
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
3

To check if a particular Id containing .reply div:

if($("#id .reply").length>0)
{
//reply exist in this id
} 

Above code works like this

$("#id .reply").length 

returns the occurrence of .reply in #id selector.

If present then return 1 else return 0.

Sunil Kumar
  • 1,389
  • 2
  • 15
  • 32
1

You are on correct path, if you want to check for unique id use #elementId

if($("#ID .reply").length > 0)
{
   //div exists
}
Satpal
  • 132,252
  • 13
  • 159
  • 168