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
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:
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.
Your 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();