How to Remove a Div But Keep Its Elements

Is there a way to remove a div but keep its elements?

This is the perfect use case of display:contents; (https://caniuse.com/#feat=css-display-contents)

display: contents causes an element's children to appear as if they were direct children of the element's parent, ignoring the element itself. This can be useful when a wrapper element should be ignored when using CSS grid or similar layout techniques.

.container {  display:flex;}
.one { display:contents;}
.one p:first-child { order:2;}
<div class="container">
<div class="one"> <p>Content 1</p> <p>Content 3</p> </div>
<p>Content 2</p>
</div>

Remove element, but keep all data and events bind

You can use .detach()

The .detach() method is the same as .remove(), except that .detach()
keeps all jQuery data associated with the removed elements. This
method is useful when removed elements are to be reinserted into the
DOM at a later time.

Also you can append the detach element to the DOM by using the return value:

var div = $("div").detach();

$(div).appendTo("body");

How can I remove an element but keep its children?

I would do something like:

$a = $("a")
$a.replaceWith($a.children());

Remove all text content from HTML div but keep HTML tags and structure

You can create a function/plugin that will recurse through elements in your top level element, removing any text nodes found:

$.fn.removeText = function(){
this.each(function(){

// Get elements contents
var $cont = $(this).contents();

// Loop through the contents
$cont.each(function(){
var $this = $(this);

// If it's a text node
if(this.nodeType == 3){
$this.remove(); // Remove it
} else if(this.nodeType == 1){ // If its an element node
$this.removeText(); //Recurse
}
});
});
}

$('#toplevel').removeText();

JSFiddle

Reference:

  • .contents()
  • .each()
  • .remove()

How can i remove all div's and other DOM HTML elements except a particular class using jQuery

It's possible to combine:

  • .clone()
  • .contents()
  • .remove()
  • .append()

Create a copy of element to add to body, remove everything from body, append the saved element.

The snippet:

var saveIt = $('.content').clone(true);
$('body').contents().remove();
$('body').append(saveIt);
.as-console-wrapper {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
<div id="livebtbox" style="display:block;">
<div id="livedrag" class="ui-draggable ui-draggable-handle">
<i class="fa fa-arrows" aria-hidden="true"
style="background:#e8e8e8;border-radius:2px;position:absolute;top:-10px;left:-10px;padding:2px;cursor:move;"></i>

<div id="live-bt" data-url="https://zeenews.india.com/hindi/live-tv">
<a>LIVE TV</a>
</div>
<div id="cripple" class="circle-rippl"></div>
</div>
</div>


<script type="text/javascript"
src="https://www.kaltura.com/p/1740481/sp/174048100/embedPlaykitJs/uiconf_id/42897261/partner_id/1740481/versions/"></script>
<script id="izootoSdk" src="https://cdn.izooto.com/scripts/sdk/izooto.js"></script>
<script src="https://hindi.cdn.zeenews.com/hindi/desktop/js/zee-hindi.js?v=1"></script>
<div id="containerbox" style="display:block;">
<div class="beforecontent" style="transform: none;">
some content here i don't want
</div>
<!-- Only the div i want to keep in body tag this is from here-->
<div class="content" style="transform: none;">
<div class="top-ad margin-auto text-center top-ad-show" style="margin: 0px auto; width: 970px; height: auto;">

<div id="div-gpt-ad-1500542080521-0" data-google-query-id="CPiRrP7w4e4CFQUZtwAd3F0ABw">

<div id="google_ads_iframe_/11440465/Zeenews_Hindi_Web/Zeenews_Hindi_AS_ATF_970x90_0__container__"
style="border: 0pt none;"><h1> SOME HEADING</h1></div>
</div>
</div>
<!-- to here -->
</div>
<style>
@media (max-width: 1362px) and (min-width: 1180px) {
.nav-s-block a {
padding: 18px 10px;
}
}

@media (min-width: 900px) and (max-width: 1042px) {
.nav-s-block a {
padding: 20px 3px !important;
font-size: 13px !important;
}
}

@media (min-width: 768px) and (max-width: 899px) {
.nav-s-block a {
padding: 20px 1px !important;
font-size: 12px !important;
}
}
</style>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.2/jquery.ui.touch-punch.min.js"></script>

<script>
$(document).ready(function () {

$('#livedrag').draggable({cancel: "#live-bt a"});
$("#live-bt a").on('touchstart click', function () {
var url = $("#live-bt").attr("data-url");
$(location).attr('href', url);
});


});

</script>


<div id="co-container" class="co-container" style="display:none;">
<div class="co-block clearfix">
<p>By continuing to use the site, you agree to the use of cookies. You can find out more by clicking
<a id="myBtn" target="_cookies" href="/cookie-policy" style="cursor: pointer;"><strong>this
link</strong></a>
</p>
<a id="myCloseBtn" style="cursor: pointer;" class="co-close">Close</a>
</div>
</div>
</div>
</body>

<style>
.modal-body {
padding: 2px 16px
}

.modal-footer {
padding: 15px;
background-color: #f44336;
color: #fff;
}

#mymodal header h2 {
font-size: 20px;
}
</style>

<script type="text/javascript" id="adg_pixel_footer_script" async=""
src="https://adgebra.co.in/afpf/afpf.js?p1=99&p2=0&p3=2&p4=2~2!zeenews.india.com&p5="></script>
<script>site = 'hi';
type = 'n';
id = 845961;
$(document).ready(function () {
if (site && type && id) {
var pvtrhost = "stats.zeenews.com";
var pvtrapp = "/apps/pvtr";
$.get("https://" + pvtrhost + pvtrapp, {site: site, type: type, id: id});
}
});</script>
<!--2021-02-11 06:26:18 PM-->

<span><iframe class="trc-hidden" id="trc-pixel-iframe-6131" name="trc-pixel-iframe-6131" width="0" height="0"
style="display:none"></iframe></span>

<div id="footer" class="co-container" style="display:none;">
<div class="co-block clearfix">
<p>By continuing to use the site, you agree to the use of cookies. You can find out more by clicking
<a id="myBtn" target="_cookies" href="/cookie-policy" style="cursor: pointer;"><strong>this
link</strong></a>
</p>
<a id="myCloseBtn" style="cursor: pointer;" class="co-close">Close</a>
</div>
</div>

Remove everything inside div but keep children with specific class name

If you make a copy of the node(s) you want to keep, you can then wipe out all the content of the container and then place the copy(ies) back in.

let copy = $("div.example-container p.element-iwant-to-keep").clone(true); // Get a copy of the node you want to keep$("div.example-container").html(copy); // Clear out the container and put in the copy
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="example-container">  <p class="element-iwant-to-keep">    this is the text of the div that i want to keep.  </p>
<ul><li>more text i dont want to keep</li></ul> <ul><li>more text i dont want to keep</li></ul> <ul><li>more text i dont want to keep</li></ul> some more text inside the main div i dont want to keep.</div>

Is it possible to remove an html element and keep your children with javascript?

It's possible with vanilla JavaScript by deep cloning the node of grandson before removing anything else. and then appending it back to the parent. Of course if you want to place it somewhere else, you need to append needed logic of DOM traversing. (CSS section is only for visual validation of the result)

const grandson = document.querySelector('.grandson');const father = grandson.closest('.father');const clonedGrandson = grandson.cloneNode(true);
father.querySelector('.son').remove();father.appendChild(clonedGrandson);
.father {  background-color: red;  padding: 20px; }  .son {  background-color: blue;  padding: 20px; }  .grandson {  background-color: green;  padding: 20px; }
<div class="father">  <fieldset class="son">    <div class="grandson">      <p>Save me</p>    </div>  </fieldset></div>

remove parent element but keep the child element using jquery in HTML

You can use replaceWith()

$('.row').replaceWith(function() {
return $('ul', this);
});

Working Demo

Remove parent div in a HTML string but keep contents

You could store the children of the fr-element div, remove everything from the row, and re-append the children:

var $row = $('<div class="content fr-box fr-inline pixer row"><div class=fr-wrapper dir=auto><div class="fr-element fr-view"dir=auto aria-disabled=false contenteditable=true spellcheck=false><div class=top-mid-float><div id=main-inner-header><h1><strong>Hello there!</strong></h1></div><div id=lower-content-header><p>Quisque tincidunt nunc in lacus consectetur, et pharetra velit pulvinar. Quisque id egestas tellus, vitae venenatis tellus. Etiam accumsan iaculis sem, in vestibulum odio tincidunt vel. Etiam justo massa, congue vulputate dui.</div></div></div></div></div>');
var children = $row.find('.fr-element').children();$row.empty().append(children);
// If you want to add the result somewhere$('body').html($row);
// Or, to turn the modified result back into an HTML stringvar finalHTMLString = $row.wrapAll('<div>').parent().html();console.log(finalHTMLString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to remove a div without using its ID

  1. test the existence:

   for (g = 0; g < numItems; g++) {
var $div = $("#tree" + g);
if ($div.length==0) continue;
var p = $div.position();

if ((p.left > (mouseX - clickRange)) &
(p.left < (mouseX + clickRange)) &
(p.top > (mouseY - clickRange)) &
(p.top < (mouseY + clickRange))) {

$div.remove();
}
}

  1. Delegate - You add a click handler every time you loop

 $('#levelWrapper').on('click','div.tree',function(e) {
getMouseCoordinates(e);
$('.tree').each(function() {
var p = $(this).position();

var i = 0,  a = 0;
function newTree() { i = $('#levelWrapper').children().length; var $newTree = $('<div/>', { 'id': 'tree' + i, 'class': 'tree' }); // .text(i); $('#levelWrapper').append($newTree);}
function positionTree() { var levelWidth = document.getElementById("levelWrapper").offsetWidth; var levelHeight = document.getElementById("levelWrapper").offsetHeight;
var treeX = Math.round(Math.random() * levelWidth); var treeY = Math.round(Math.random() * levelHeight);
document.getElementById("tree" + i).style.left = treeX + "px"; document.getElementById("tree" + i).style.top = treeY + "px";}
function createTree() { a += 1; if (a == 20) { newTree(); // new div positionTree(); // position div a = 0; // reset counter for new div i++; // new ID for new div }}
function getMouseCoordinates(e) { var offset = $('#levelWrapper').offset(); mouseX = Math.round(e.clientX - offset.left); mouseY = Math.round(e.clientY - offset.top);}
var clickRange = 100;

function mainLoop() { createTree(); requestAnimationFrame(mainLoop);}

$(function() { $('#levelWrapper').on('click','div.tree',function(e) { getMouseCoordinates(e); $('.tree').each(function() { var p = $(this).position();
if ((p.left > (mouseX - clickRange)) & (p.left < (mouseX + clickRange)) & (p.top > (mouseY - clickRange)) & (p.top < (mouseY + clickRange))) {
$(this).remove(); } }); }); requestAnimationFrame(mainLoop);});
#levelWrapper {  position: relative;  top: 25px;  width: 1100px;  height: 700px;  margin: auto;  border: 1px solid red;}
.tree { position: absolute; background: green; height: 12px; width: 12px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><div id="levelWrapper"></div>


Related Topics



Leave a reply



Submit