How to clear all <div>s’ contents inside a parent <div>? - javascript

I have a div <div id="masterdiv"> which has several child <div>s.
Example:
<div id="masterdiv">
<div id="childdiv1" />
<div id="childdiv2" />
<div id="childdiv3" />
</div>
How to clear the contents of all child <div>s inside the master <div> using jQuery?

jQuery's empty() function does just that:
$('#masterdiv').empty();
clears the master div.
$('#masterdiv div').empty();
clears all the child divs, but leaves the master intact.

jQuery('#masterdiv div').html('');

Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.
$('#masterdiv div').empty();
Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.

I know this is a jQuery related question, but I believe someone might get here expecting a pure Javascript solution. So, if you were trying to do this using js, you could use the innerHTML property and set it to an empty string.
document.getElementById('masterdiv').innerHTML = '';

jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/

If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);

The better way is :
$( ".masterdiv" ).empty();

$("#masterdiv div").text("");

$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")

$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div

You can use .empty() function to clear all the child elements
$(document).ready(function () {
$("#button").click(function () {
//only the content inside of the element will be deleted
$("#masterdiv").empty();
});
});
To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/

When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();

$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});
or
$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});

try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();

Related

JQuery how to find the closest element that is neither a parent nor a child of the current element?

Say I have HTML that looks like this:
<div>
<div>
<div class="calendar start">
</div>
</div>
<div>
<div class="calendar end">
</div>
</div>
</div>
We can assume that the start and end will always be on the same "level" of a branch from each other, and will at some point share a common parent.
Without knowledge of the exact HTML structure, how would I find calendar end from calendar start? What if they are nested further down?
Edit: For clarification. I want to start at start's parent. Search all child elements for end. Then move to the next parent, and search all child elements...etc till I find end. I am wondering if this is possible with built in JQuery functions, without writing my own DOM traversal logic.
You can do it like below, But it is a costlier process.
var parentWhichHasCalEnd =
$($(".calendar.start").parents()
.get().find(itm => $(itm).find(".calendar.end").length));
var calEnd = $(".calendar.end", parentWhichHasCalEnd);
DEMO
Explanation: We are selecting the .start element first, then we are retrieving its parent elements. After that we are converting that jquery object collection to an array of elements by using .get(). So that we could use .find(), an array function over it. Now inside of the callBack of find we are checking for .end over each parent element of .start, if a parent has .end then we would return that parent. Thats all.
You could get more understanding, if you read .get(), .find(), and arrow functions.
You can use jQuery#next() method from .start parent element
var startSelector = $('body > div > div:nth-child(3) > .start')
var endSelector = secondStart.parent().next().find('.end');
I think this method is faster rather than jQuery#children() method, but you can benchmark it if you want to
btw you may check my answer based on this JSBin
i don't know if i got this right but have you tried children function in jquery
$( ".calender" ).children( ".end" )
and for the parent you can use parent() function so you can first check the parent then the children or vicversa
edit:
if you dont know the exact structure the better way is to find the common parent and then search it's children :
$( ".calender.start").closest('.common-parent').children('.calender.end');
closest function give the nearest parent
Try:
$('.start').parent().parent().find('.end');

Javascript get content of previous element

i've a question about 'this'.
With this i can get the content of actual element, but i want to get the content of previous element.
function deneme2(e){
alert(e.innerHTML);
}
Demo: http://jsfiddle.net/aldimeola1122/247m3xec/
Is there any function to get the content of child or parent element?
How can i achieve that?
Thanks in advance.
You can use previousElementSibling which gives the previous sibling element to the current element.
function deneme2(e){
alert(e.previousElementSibling.innerHTML)
}
DEMO
It isn't realy clear to me if you want the parent-element or the sibbling element. If you want the html of the parent element of e, you can use following code:
function deneme2(e){
alert(e.parentNode.innerHTML);
}
If you want the html of the child-element of e, you can use:
e.children[i].innerHTML
With i being the index of the element.
Check this:
function deneme2(e){
alert($( "#"+ e.id).prev().html());
}
Or try the post of Amit Joki. This is the same, but my post with using JQuery api.
DEMO

Move a Element in Jquery

I want to prepend a Font Element in HTML within a DIV. There will be multiple div within the same page with unique Id.
<div id="id-unknown">
"Some Text"
<font color="red">*</font>
</div>
To
<div id="id-unknown">
<font color="red">*</font>
"Some Text"
</div>
I used this Jquery code to achieve it but it gets all the fonts and prepend to every div element
$("font").prependTo($("font").parent());
http://jsfiddle.net/s4Ehw/
If you only want to do this for specific divs, just add the ID selector and use .each to obtain a reference to the specific element (this)
$('#id1, #id2, #id3').children('font').each(function() {
$(this).prependTo(this.parentNode);
});
If it so happens that every font tag needs this change, use the same .each construct as above but use $('font'), per your original code and Si Donaldson's answer.
For extra performance, replace the function body with:
var parent = this.parentNode;
parent.insertBefore(this, parent.firstChild);
i.e. replacing the jQuery calls with direct DOM manipulation.
You need to itterate through each one first using $.each and then you can work on each one individually!
http://jsfiddle.net/sidonaldson/s4Ehw/2/
$("font").each(function(){
$(this).prependTo($(this).parent());
});
use jQuery each function for manage elements in cycle
jsfiddle.net/s4Ehw/6/
$("font").each(function(){
$(this).prependTo($(this).parent());
})
$.each($("font"), function(index, element) {
console.log($(element));
$(element).prependTo($(element).parent());
});

Variable with HTML content parsing

I have this variable called $reservas that contains a string with HTML Tables. I want to remove parts of the tables (.tdRemove), BEFORE I assign them to the div #cenas.
if ($reservas){
$($reservas).find('.tdRemove').each(function(){
console.log($(this).html());
$(this).remove();
});
$("#cenas").html($reservas);
}
I tried this, but it doesn't seem to remove anything.
I've also tried:
$($reservas).find('.tdRemove').remove(); and $($reservas).remove('.tdRemove');
Nothing works. Any suggestions?
Is there any way to tell jQuery that the variable holds html content, and should be parsed as that? If so, how? ..
After converting your string to a jQuery object, it is now a series of DOM objects (in a document fragment) held in the jQuery object. After removing the .tdRemove objects in that fragment, you can then just append that directly to your DOM. No need to go back to HTML:
if ($reservas){
var item = $($reservas);
item.find('.tdRemove').remove();
$("#cenas").empty().append(item);
}
Also, your code didn't work because the $reservas string of HTML was never modified.
I think, from what the documentation tells me, you can only remove() what is already inside the DOM.
Remove the set of matched elements from the DOM.
Maybe you want to add your table first, set it to ? display: none`, then filter for elements to remove and finally display the table.
if ($reservas) {
$("#cenas")
.hide()
.html($reservas)
.find('.tdRemove').each(function(){
console.log($(this).html());
$(this).remove();
})
.show();
}

Combine after() and slideDown()

I am adding an element on a certain condition. But I don't want it suddenly appear but rather would like to slide it down. Here's how I add it:
$('.myDiv').after('<div>added content</div>');
How do I combine it with slideDown?
Try this instead :
$(".myDiv").after("<div style='display:none;'>added content</div>");
$(".myDiv").next("div").slideDown();
Good Luck !!
Try this out:
$('.myDiv').after('<div style="display:none">added content</div>').next().slideDown();
You need to use .next() on the div to which it is attached because .after()... adds the element as a sibling to the div to which it is added
Try this
$('.myDiv').after('<div style="display:none;" class="newDiv">New Content</div>');
$('.myDiv').next('.newDiv').slideDown();
first make sure the new content that you input is hidden using .newdiv{display:none;} either in your css file or inline code like: <div style="display:none;">
then use a callback function to only start after the code was inserted in the document when you used the after() method.
$('.myDiv').after('<div class="newdiv">added content</div>', function(){
$('.newdiv').slideDown();
});

Categories