Search code examples
jquerychatappendchild

If child element has class then alert


I am trying to make a simple chat action where me is the first user and you is the second user. All I am trying to put input text into ul li. condition if last ul has class me then alert me else alert you. Kindly advice.

Following is my code.

HTML

<div class="chat-left">
    <div class="msg-area">
        <ul class="me">
            <li>what is this msg</li>
        </ul>
        <ul class="you">
            <li>others message</li>
        </ul>
    </div>
    <form id="me">
        <input type="text" name="mymsg" />
        <input type="submit" class="submit" name="submit" />
    </form>
</div>

jQuery

$(document).ready(function () {
    $('#me').submit(function (event) {
        event.preventDefault();
        console.log('left');
        var $mymsg = $('input[type="text"]').val();
        $(this).siblings('.msg-area ul').each(function () {
            if ($(this).hasClass('me')) {
                console.log('me');
            }
        });
    });
});

Solution

  • The selector siblings('.msg-area ul') won't work because ul is not a sibling element, you need to use siblings('.msg-area').find('ul')

    You don't need to have a loop to do that

    $(document).ready(function() {
      $('#me').submit(function(event) {
        event.preventDefault();
    
        var mymsg = $(this).find('input[type="text"]').val();
    
        var $last = $(this).siblings('.msg-area').find('ul:last');
        if ($last.hasClass('me')) {
          $('#log').html('me')
        } else {
          $('#log').html('you')
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="log"></div>
    <div class="chat-left">
      <div class="msg-area">
        <ul class="me">
          <li>what is this msg</li>
        </ul>
        <ul class="me">
          <li>others message</li>
        </ul>
      </div>
      <form id="me">
        <input type="text" name="mymsg" />
        <input type="submit" class="submit" name="submit" />
      </form>
    </div>