Clearing div child elements without removing from the DOM - javascript

My goal is, using Jquery or vanilla JS, to clear the inner text only of a div and each of its child elements while keeping all elements intact after the fact. In the example below, the div is student_profile.
Answers on SO have recommended the functions .html('') and .text('') but, as my example shows below, this completely removes the child element from the DOM (my example shows only one function but both actually remove the element). Is there a function that would remove all of the text from the current div and child divs while keeping the elements themselves intact?
Any advice here would be appreciated!
function cleardiv() {
console.log(document.getElementById("student_name"));
$('#student_profile').html('');
console.log(document.getElementById("student_name"));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='student_profile'>
<h1 id="student_name">Foo Bar</h1>
<p id="student_id">123</p>
<p id="studen_course">math</p>
<p id="last_reported">2021-01-01</p>
</div>
<button onclick="cleardiv()">Clear</button>

One option is to select all text node descendants and .remove() them, leaving the actual elements intact:
const getTextDecendants = (parent) => {
const walker = document.createTreeWalker(
parent,
NodeFilter.SHOW_TEXT,
null,
false
);
const nodes = [];
let node;
while (node = walker.nextNode()) {
nodes.push(node);
}
return nodes;
}
function cleardiv() {
for (const child of getTextDecendants($('#student_profile')[0])) {
child.remove();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='student_profile'>
<h1 id="student_name">Foo Bar</h1>
<p id="student_id">123</p>
<p id="studen_course">math</p>
<p id="last_reported">2021-01-01</p>
</div>
<button onclick="cleardiv()">Clear</button>

You can try the selector #student_profile * to include all the child elements.
function cleardiv() {
console.log(document.getElementById("student_name"));
$('#student_profile *').text('');
console.log(document.getElementById("student_name"));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='student_profile'>
<h1 id="student_name">Foo Bar</h1>
<p id="student_id">123</p>
<p id="studen_course">math</p>
<p id="last_reported">2021-01-01</p>
</div>
<button onclick="cleardiv()">Clear</button>

If it's only direct children you're looking to affect, you can iterate the childNodes of the parent element. This will clear both element nodes as well as non-element nodes such as text nodes. Here using the NodeList#forEach() method provided by the returned NodeList.
function cleardiv() {
document.getElementById('student_profile')
.childNodes
.forEach((node) => (node.textContent = ''));
console.log(document.getElementById('student_name'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='student_profile'>
<h1 id="student_name">Foo Bar</h1>
<p id="student_id">123</p>
<p id="studen_course">math</p>
<p id="last_reported">2021-01-01</p>
</div>
<button onclick="cleardiv()">Clear</button>

Related

Finding the next Canvas id in Jquery

When looking for the next element id in Jquery the simplest solution is to use closest(element). but it is not working for Canvas and I don't know why.
$('a.findNext').click(function() {
debugger;
var nextSectionWithId = $(this).closest("canvas").nextAll("canvas[id]:first");
if (nextSectionWithId) {
var sectionId = nextSectionWithId.attr('id');
$("#test").text(sectionId)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section_1">
Find
</div>
<div></div>
<canvas id="section_3"></canvas>
<canvas id="section_4"></canvas>
<div id='test'></div>
Demo :
http://jsfiddle.net/jtdgo304/6/
.closest will select the nearest ancestor matching the selector. But the .findNext element does not have a canvas ancestor.
If you want to get the next ancestor, you'll need to first navigate to an element that's a sibling of the canvas (which is the #section_1 here), then use .nextAll.
You should also check the .length of the jQuery collection to see if it matches any elements.
$('a.findNext').click(function() {
const nextSectionWithId = $(this).parent().nextAll("canvas[id]:first");
if (nextSectionWithId.length) {
const sectionId = nextSectionWithId.attr('id');
$("#test").text(sectionId)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section_1">
Find
</div>
<div></div>
<canvas id="section_3"></canvas>
<canvas id="section_4"></canvas>
<div id='test'></div>

Find elements of similar hierarchy by JavaScript (for web scraping)

For example, when I select one of the p.item-title elements below, all p.item-title elements should be found (not by the class name). Also, when I select one of the table elements below, all similar tables should be found. I need this for web scraping.
<div>
<div>
<p class="item-title">...</p>
<table>...</table>
</div>
</div>
<div>
<div>
<p class="item-title">...</p>
<table>...</table>
</div>
</div>
jQuery's siblings() method is similar in concept, but it finds similar elements under the same parent node. Is there any method or library to find similar elements from different parent nodes?
Just do querySelectorAll by the path (hierarchy) you want:
var allElements = document.querySelectorAll("div > div > p");
allElements.forEach(p => console.log(p));
<div>
<div>
<p class="item-title">Text 1</p>
<table>...</table>
</div>
</div>
<div>
<div>
<p class="item-title">Text 2</p>
<table>...</table>
</div>
</div>
Try this:
jQuery.fn.addEvent = function(type, handler) {
this.bind(type, {'selector': this.selector}, handler);
};
$(document).ready(function() {
$('.item-title').addEvent('click', function(event) {
console.log(event.data.selector);
let elements = document.querySelectorAll(event.data.selector);
elements.forEach(e => console.log(e));
});
});
Thanks to Jack, I could create a running script.
// tags only selector (I need to improve depending on the use case)
function getSelector(element){
var tagNames = [];
while (element.parentNode){
tagNames.unshift(element.tagName);
element = element.parentNode;
}
return tagNames.join(" > ");
}
function getSimilarElements(element) {
return document.querySelectorAll(element);
}

using jquery remove part of a cloned element

having a difficult time removing a div inside of a cloned element. run the snippet and notice the do not clone me part gets appended even though it is removed.
let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
clone me
<div class="noClone">
do not clone me
</div>
<button class="clonebtn"> clone it </button>
</div>`
$(document).ready(function() {
let content = $(myhtml);
$('.row').append(content);
$('.row').on('click', '.clonebtn', function() {
let container = $(this).closest('.mycontainer');
let clonedContainer = container.clone();
clonedContainer.remove('.noClone');
$('.row').append(clonedContainer);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
</div>
</div>
or run the fiddle here https://jsfiddle.net/k6jz9xe2/3/
You need to use .find() to find all elements inside the parent div with a class of noClone to remove.
$(selector).remove(anotherselector) in jQuery only removes any elements matching anotherselector from the Array returned by selector. The selector given to the remove() function is only applied to the elements contained in the jQuery collection not to the children of those elements. It is analogous to $(selector).filter(anotherselector).remove().
Consider the following HTML and jQuery code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
Foo
<div id="bar">Bar</div>
</div>
<script>
$('#foo').remove('#bar');
</script>
You may expect that the div with the id "bar" inside the div with the id "foo" will be removed, but this is not the case. Why? The $('#foo') selector returns an Array with just one item: the div with the id of "foo". jQuery attempts to filter through the Array and find an element matching the $('#bar') selector. No element is found and nothing will happen.
The following selector, however, will remove the div with the id of "bar".
$('div').remove('#bar');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
Foo
<div id="bar">Bar</div>
</div>
<script>
$('div').remove('#bar');
</script>
The $('div') selector returns an Array with all the divs on the page. jQuery filters through all of the divs to find an div matching the $('#bar') selector (having an id of "bar"). Having found one, it removes it.
let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
clone me
<div class="noClone">
do not clone me
</div>
<button class="clonebtn"> clone it </button>
</div>`;
$(document).ready(function() {
let content = $(myhtml);
$('.row').append(content);
$('.row').on('click', '.clonebtn', function() {
let container = $(this).closest('.mycontainer');
let clonedContainer = container.clone();
clonedContainer.find('.noClone').remove();
$('.row').append(clonedContainer);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
</div>
</div>
let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
clone me
<div class="noClone">
do not clone me
</div>
<button class="clonebtn"> clone it </button>
</div>`
$(document).ready(function() {
let content = $(myhtml);
$('.row').append(content);
$('.row').on('click', '.clonebtn', function() {
let container = $(this).closest('.mycontainer');
let clonedContainer = container.clone();
clonedContainer.find('.noClone').remove();
$('.row').append(clonedContainer);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
</div>
</div>

Is there any inbuild function in javascript to select last element with using class selector or element selector?

similar type of question is already asked link.but my question is bit diffrent.
in my program frequently occur new element with using dom. here my question is
is there any built in function in javascript that i can select last element frequently?
here is an example
var para = document.createElement("div");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
given program append div element frequently and also i want to select div element frequently. similar with a class
thankyou in advance
Use querySelectorAll and pass the class selector. Then target the last element and do whatever
let getAllElem = document.querySelectorAll('.test');
getAllElem[getAllElem.length - 1].classList.add('green')
.green {
color: green
}
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
<div class="test">6</div>
no there is not any built in function in java script but u should try below logic and use it with jquery like $(last_selector(".lastclass")).click(); for select last class and $(last_selector("div")).click(); for elect last element
function last_selector(select){
if(select[0]=="."){
var allSelect = document.getElementsByClassName(select.slice(1));
}
else{
var allSelect = document.getElementsByTagName(select);
}
return allSelect[allSelect.length-1];
}
console.log(last_selector("div"))
console.log(last_selector(".last"))
<div>hello</div>
<div>hello</div>
<div class="last">last class</div>
<div>last element</div>
It will give last span text inside every Div using $(elementName).children("span:last").text()
$(document).ready(function(){
console.log($('div').children("span:last").text())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="time">2016</span><br>
<span class="time">2017</span><br>
<span class="time">2018</span><br>
<span class="time">2019</span><br>
<span class="time">2020</span><br>
<span class="time">2021</span><br>
<span class="time">2022</span><br>
<span class="time">2023</span><br>
<span class="time">2024</span> <br>
</div>

Create element in another div element using classname

I'm trying to create new elements in another pre-existing <div> element using js DOM.
I'm able to do this if that <div> is called using id but I want to accomplish this by class
This is what I have so far
<html>
<body>
<button onclick="whiskey()">go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p> This is just a control Element</p>
</div>
<script type="text/javascript">
function whiskey(){
var input=document.createElement("input");
input.type="text";a
input.id="sad";
var newdiv=document.createElement("div");
newdiv.appendChild(input);
/* this part doesn't work */
var maindiv=document.getElementsByClassName("pagination-pagination-right");
maindiv.appendChild(newdiv);
}
</script>
</body>
</html>
getElementsByClassName() returns a HTMLCollection which is an array like collection of object, which does not have the appendChild() method. You need to get the first element form the list using an index based lookup then call the appendChild()
function whiskey() {
var input = document.createElement("input");
input.type = "text";
//ID of an element must be unique
input.id = "sad";
var newdiv = document.createElement("div");
newdiv.appendChild(input);
var maindiv = document.getElementsByClassName("pagination-pagination-right");
maindiv[0].appendChild(newdiv);
}
<button onclick="whiskey()">go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p>This is just a control Element</p>
</div>
You could also do this by using jQuery
HTML
<button>go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p> This is just a control Element</p>
</div>
jQuery
$(function(){
$('button').click(function(){
$('<div>A</div>').appendTo('.pagination-pagination-right');
});
});
You can replace $('<div>A</div>') part with whatever element you want to append in your <div>
Fiddle here

Categories

Resources