简体   繁体   中英

why parent is not working in jquery?

could you please tell me why parent function is not working properly ?

here is my code

https://jsbin.com/gefacenefi/edit?html,js,output

 $(function () {

        $('.add').click(function () {
            $('.item').parent('li.nn').css('color', 'red');
        });

    });

Expected output this text to be red

<li class="nn">bhiooo</li>

You are trying to call a parent of a different node. Try this

$('.add').click(function () {
  $('.item').parent().siblings('li.nn').css('color', 'red');
});

Please do the following:

$(function () {
    $('.add').click(function () {
      $('.item').parent().siblings('li.nn').css('color', 'red');
    });
});

Also you are not closing your li element properly. The structure should be like following:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width">
   <title>JS Bin</title>
   <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
   <button class="add">filler</button>
   <div>
      <ul>
         <li class="nn">bhiooo</li>
         <li class="m">hello22
            <ul class="item">
                <li class="abc">123</li>
                <li class="pp">12</li>
                <li class="abc">78</li>
                <li class="ac">13</li>
                </li>
            </ul>
         </li>
      </ul>
   </div>
</body>
</html>

Your ul .item is not under .nn .

Change the HTML, or adapt you JS

$('.item').parent().prev('li.nn').css('color', 'red');

Try the following code

$('.add').click(function () {
  $('.item').parents().find('.nn').css('color', 'red');
});

Here is the working jsfiddle: https://jsfiddle.net/nq9tzafz/

I think it should helps you

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