最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using remove as opposite of append not working - Stack Overflow

programmeradmin1浏览0评论

Here's how I append the value:

$('<div>someText</div>').appendTo(self);

And here's how I want to remove it:

$(self).remove('<div>someText</div>');

The appending works, the removing doesnt. What am I doing wrong?

Here's how I append the value:

$('<div>someText</div>').appendTo(self);

And here's how I want to remove it:

$(self).remove('<div>someText</div>');

The appending works, the removing doesnt. What am I doing wrong?

Share Improve this question asked Feb 27, 2013 at 9:05 petko_stankoskipetko_stankoski 10.7k42 gold badges134 silver badges234 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

The .remove() function takes a selector to filter the already matched elements, not to match elements inside of them. What you want is something like this:

$(self).find('div:contains(someText)').remove();

That will find a <div> element containing the text someText inside of whatever element self is, then removes it.

The API http://api.jquery./remove/ sais that a selector is required.

Try $(self).remove('> div'); This will remove the first childs of div.

You can use $(self).filter('div:contains("someText")').remove(); to remove a div with a specific content or $(self).find('> div').remove(); to remove the first childs of div.

EDIT: removed first version I posted without testing.

It most likely has to do with the scope of self. Since you've named it self I am assuming that you are getting this variable using $(this) on the click event. If that's the case, and you want to call the remove method, you can only do so from within the same function. Otherwise you need to either store the element in a variable or provide another selector to access it.

Example:

<div class="div1"></div>

this will be the div with the click event

$(document).ready(function(){
    var self = null;
    $('.div1').click(function(e){
         self = $(this);
         var itemToAdd = '<div>SomeText</div>';
         $(itemToAdd).appendTo(self);
    });
    // to remove it
    // this will remove the text immediately after it's placed 
    // this call needs to be wrapped in a function called on another event
    $('.div1').find('div:contains(someText)').remove();      
});    
发布评论

评论列表(0)

  1. 暂无评论