How can I reset after append() or before()? Please help. Many thanks in advance.
if((#tag_id).text() == 'something'){
$(#tag_id).before("x");
}
// I want to reset the #tag_id to empty
$(#tag_id).val(''); // this doesn't work
How can I reset after append() or before()? Please help. Many thanks in advance.
if((#tag_id).text() == 'something'){
$(#tag_id).before("x");
}
// I want to reset the #tag_id to empty
$(#tag_id).val(''); // this doesn't work
Share
Improve this question
asked Aug 10, 2010 at 18:44
DGTDGT
2,65413 gold badges42 silver badges60 bronze badges
4 Answers
Reset to default 5Your code example uses .before()
. In this case, it would be better if .before()
was given an element around x
instead of just the text.
Then you could do this:
// Wrap the "x" that you're inserting with <span> tags
$('#tag_id').before('<span>x</span>');
// Use .prev() to reference the new <span> and remove it
$('#tag_id').prev().remove('span');
Remember that using .before()
does not place anything inside the #tag_id
, but instead places it before the #tag_id
.
If you meant for the content to go inside #tag_id
but at the beginning, you would use .prepend()
.
If your code is using .append()
, one option would be to keep a reference to the element you're appending, and use that to remove it later.
var $appendElem = $('<div>some appended element</div>');
$appendElem.appendTo('#tag_id');
Then you can remove it via the same reference.
$appendElem.remove();
// or
$appendElem.detach();
If you want to remove the html inside of it, use:
$('#tag_id').html('');
If you want to remove the id
attribute, use the removeAttr
:
$('#tag_id').removeAttr('id');
More Info:
- http://api.jquery./removeAttr/
- http://api.jquery./html/
If there are no handlers you can use .html()
like this:
$('#tag_id').html('');
However if there are any event handlers or data on any objects in there you should use .empty()
instead, like this:
$('#tag_id').empty();
.html('')
won't clean up data/event handlers in $.cache
where .empty()
and .remove()
will, if you're unsure, use .empty()
to avoid potential memory leaks.
Is this what you want?
$("#tag_id").html("");