Add Class To Closest Element [duplicate]

2019-08-28 18:24发布

This question already has an answer here:

I'm trying to add a class to dynamically created objects, but there is something that is going wrong here. And I can't get it to work!

Any ideas?

<span class="status"><div class="like_button"></div></span>

 <script>  
   $(this).closest('span').find('.like_button').addClass('liked')
</script>

UPDATE:

Thing is I am having a Facebook like button (created with the API not the regular one) inside each of the elements, and needs to check its status before I can add class "liked" or "unliked". So all the div's with class "item" is created in a PHP loop. And also I understand its not good to run the script several times in a loop. But I need to get further in the testings here :)

<div class="item">
 <span class="status"><div class="like_button"></div></span>
 <script>  
 $(this).closest('span').find('.like_button').addClass('liked')
 </script>
 </div>

 <div class="item">
 <span class="status"><div class="like_button"></div></span>
 <script>  
 $(this).closest('span').find('.like_button').addClass('liked')
 </script>
 </div>

 <div class="item">

 <span class="status"><div class="like_button"></div></span>
  <script>  
 $(this).closest('span').find('.like_button').addClass('liked')
 </script>
 </div>

 <div class="item">
 <span class="status"><div class="like_button"></div></span>
  <script>  
 $(this).closest('span').find('.like_button').addClass('liked')
 </script>
 </div>

2条回答
虎瘦雄心在
2楼-- · 2019-08-28 19:04

When the code in the script tag will be running, the <span> will be the last loaded tag.

That beign said, you can do this :

$('span:last').find('.like_button').addClass('liked')

Fiddle : http://jsfiddle.net/NRUuV/

查看更多
迷人小祖宗
3楼-- · 2019-08-28 19:04

Assuming $(this) is span: $(this).next().addClass('liked')

查看更多
登录 后发表回答