Let's say I have some sibling DOM elements that exist only within a jQuery selection:
var $container = $('<div></div><span></span>');
I want $div to only contain <div></div>, so I try to remove the <span>:
$container.find('span').remove();
// Note that span still exists:
console.log($div.length === 2);
What's the right way to solve this?
Your current selection is your <div> element. You need to find your span within there and call .remove() on that.
The parameter passed to .remove() does not find elements within the current collection, it filters it.
var $div = $('<div><span></span></div>');
$div.find('span').remove();
This doesn't modify the current selection so this isn't ideal, but I ended up finding a solution using .not():
$div = $div.not('span')
Related
How do I only get the next element of the element I've already traversed to for a jQuery prepend.
For each .element-to-insert-into I'd like to prepend that element's next children.
Below does not work. I believe I'm not using "this" correctly:
jQuery('.element-to-insert-into').prepend(jQuery(this).next('.parent-element').children('child-id-like-to-prepend'))
You could use an each loop:
jQuery('.element-to-insert-into').each(function(index, element) {
var $current = $(element);
$current.prepend($current.next('.parent-element').children('#child-id-like-to-prepend'));
// as ids are meant to be unique, you could just prepend the targeted id:
$current.prepend($('#child-id-like-to-prepend'));
});
If I have a JQuery object which contains elements already being in the DOM, the remove function will properly remove them from it.
However, I would like to remove specific elements which are not yet added to the DOM, only existing in a JQuery object, like the following:
var $div = $("<div><span class='sample'></span></div>");
$div.remove(".sample");
console.log($div.html()); // prints out the original HTML, inner span is not removed
If you pass the selector to remove() then the selector will be applied to the passes set of elements in your case $div which does not contain the sample element, it is a descendant of the elements referred by $div. So you need to use .find() to find the element and remove it
var $div = $("<div><span class='sample'></span>some content</div>");
$div.find(".sample").remove();
$('#result').text($div.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
var $div = $("<div>outside of sample <span class='sample'>inside of sample</span></div>");
$div.find(".sample").remove();
alert($div.html());
demo: http://jsfiddle.net/3p0zsa8h/
The $div holds the jquery object and they treated as a jquery object.
var $div = $("<div><span class='sample'>4334</span></div>");
$div.find(".sample").remove();
console.log($div.html());
DEMO
Basically $div would holds the object of the wrapper div element, so by using it, you could select its descendant by using .find(selector) function and after that remove it by .remove()
Try,
var $div = $("<div><span class='sample'></span>hai</div>");
$div.find('.sample').remove();
alert($div.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I'm dynamically creating a div like this:
var gameScoreDiv= document.createElement('div');
gameScoreDiv.innerHTML= 'Score: 0';
wrapperDiv.appendChild(gameScoreDiv);
Later I need to remove this div from DOM. How can I get rid of that div?
Is it possible to simply delete the gameScoreDiv variable and have it remove also the DOM element (I have a feeling the answer is no)?
2019 update
You can remove node with ChildNode.remove() now:
gameScoreDiv.remove()
It's supported by every major browser with the not surprising exception of IE (for which you can add a tiny polyfill though, if needed).
You can do:
gameScoreDiv.parentNode.removeChild(gameScoreDiv);
or, if you still have reference to the wrapperDiv:
wrapperDiv.removeChild(gameScoreDiv);
In jQuery it would be:
$(gameScoreDiv).remove();
but this will use the parentNode way, see the source.
You're looking for the removeChild method.
In your case I see that wrapperDiv is the parent element, so simply call it on that:
wrapperDiv.removeChild(gameScoreDiv);
Alternatively, in another scope where that isn't available, use parentNode to find the parent:
gameScoreDiv.parentNode.removeChild(gameScoreDiv);
you can give your dynamically created div an id, and later you can see if any element with this id exists, delete it. i.e.
var gameScoreDiv= document.createElement('div');
gameScoreDiv.setAttribute("id","divGameScore");
gameScoreDiv.innerHTML= 'Score: 0';
wrapperDiv.appendChild(gameScoreDiv);
and later:
var gameScoreDiv= document.getElementById('divGameScore');
wrapperDiv.removeChild(gameScoreDiv);
You can try this:
gameScoreDiv.id = "someID";
//Remove the div like this:
var element = document.getElementById('someID');
element.parentNode.removeChild(element);
Given HTML:
<div id="div-a"></div>
<div id="div-b"></div>
<div id="div-c"></div>
And a previously-created jQuery selection:
var $divs = $("div");
How can I select a particular div in that selection by its id?
Note: the $divs selection has not yet been appended to the DOM, so I can't just select directly (e.g. $("#div-b")).
find() selects descendants of a selection, so this does not work:
$divs.find("#div-b");
has() / :has() selects elements that contain an element with the specified selector, so this does not work:
$divs.has("#div-b");
You want to use filter() to reduce the set/.
var elem = $divs.filter("#div-b");
I think you are looking for filter():
var $subset = $divs.filter("#div-b");
If you want to only examine elements within a particular jQuery object that you've already created, you can use the .filter() method:
var $divs = $("div");
var item = $divs.filter("#div-a");
This will examine only the elements within the $divs jQuery object so see if any of them match the selector "#div-a" and will return to you a new jQuery object that contains only the matches (either zero or one object in this case).
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?
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.com/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();
});