How to remove a parent node with all its children - javascript

I am learning the basics of javascript. now it DOM and i am stuck here, How can i remove a parent node with all its chldren. eg say i have the html code like this.
<ul id ="parent">
<li>Hi</li>
<li>How</li>
<li>Are</li>
<li>You</li>
</ul>
i wand to delete the <ul> element with all its child <li> nodes. I tried it to do like this document.getElementById('parent').removeNode(true); but its not working. Can anyone help me here. ?

You need to get a handle to the ul element then ask its parent element to delete it by passing the ul handle the parent's removeChild method.
This is how you would do it without the jQuery framework:
var x = document.getElementById('parent');
x.parentNode.removeChild(x);
Of course if you used jQuery it would be simple like this:
$("#parent").remove();

try this:
var childNode = document.getElementById("parent");
childNode.parentNode.removeChild(childNode);

Related

Questions about how to use javascript to increase virtual nodes

I have a set of ui and li structures. Currently, I have a requirement to concatenate the API to form 4 lis of data and put them behind the original li to add! I use the appendChild method, but you need to use this method first Create a node let div = document.createElement('div'); But this will cause the newly created label to add a div, which is a label I don't want. I would like to ask if it is possible to create a virtual empty node and put li in it ? I don't know how to do it specifically, and hope to get your help. I wrote an example such as the following case code to simulate my problem, thank you PS: I have tried to use innerHTML, but this will overwrite the original content when adding data in my actual project, so it does not work .
let str;
let wrap = document.querySelector('.wrap');
let div = document.createElement('div');
str += `<li>5555</li>
<li>6666</li>
<li>7777</li>
<li>8888</li>
`
div.innerHTML = str;
wrap.appendChild(div);
<ul class="wrap">
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
</ul>
Is it possible to create a virtual empty node and put <li> elements in it?
Yes, this exactly what a DocumentFragment does. Once you append the fragment to the <ul>, the intermediate "virtual" node is skipped and its contents are transferred.
However, a fragment does not have an .innerHTML property. For your use case, better use insertAdjacentHTML:
const wrap = document.querySelector('.wrap');
const str = `<li>5555</li>
<li>6666</li>
<li>7777</li>
<li>8888</li>
`;
wrap.insertAdjacentHTML('beforeend', str);
<ul class="wrap">
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
</ul>
You added the jquery tag, so I am going to use it because it's easier that way. With jQuery you can add multiple <li> tags at once, which is preferred because each DOM update is expensive.
let html = `<li>5555</li>
<li>6666</li>
<li>7777</li>
<li>8888</li>`;
$('.wrap').append(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="wrap">
<li>1111</li>
<li>2222</li>
<li>3333</li>
<li>4444</li>
</ul>

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');

How to get parent element?

I have this part of HTML:
<div id="menu">
<ul>
<li>Startseite</li>
<li class="active">Brillengläser</li>
<li>Komplettbrille</li>
<li>Sportbrillen</li>
<li>Marketing</li>
<li>Statistik</li>
</ul>
</div>
I want to remove class="active" parameter and set it in li tag where I have href="/pacmodule/completeglass" atribute.
First part I successfully done with jquery:
$("#menu").find("ul:first").find(".active").removeClass("active");
But I have problems with second part. This select just a tag:
$('a[href="/pacmodule/completeglass"]').parent().html();
And this all ul tag:
$('a[href="/pacmodule/completeglass"]').parent().parent().html();
How can I set class="active" attribute in li tag where href="/pacmodule/completeglass"
Thank you for help.
You do not need the html() calls. They just return the innerHTML as a string. You probably expected that would return the outerHTML (for the outerHTML use something like ...parent()[0].outerHTML)
Try this:
$('a[href="/pacmodule/completeglass"]').closest('li').addClass('active');
It will find the anchor based on the href = "/pacmodule/completeglass", then find the closest ancestor that is an LI, then add the class active to it.
closest is the most useful way to find an ancestor of a specific type. It is better than using parent() as closest copes with the HTML structure changing.
Note: If you explain the overall aim, there may be better ways to do this than searching for the link href :)
Update
You do not want to remove the previous selection with this as it is too specific:
$("#menu").find("ul:first").find(".active").removeClass("active");
try this instead:
$("#menu li.active").removeClass("active");
.closest()
$("li").removeClass("active").find($('a[href="/pacmodule/completeglass"]')).closest('li').addClass('active');
DEMO
Easily do this (into your js document):
$("#menu li").removeClass("active");
$('a[href="/pacmodule/completeglass"]').parent().addClass("active");
$("#menu").find("ul:first").find(".active").removeClass("active");
This can be made more effective writing it as:
$("#menu").find("li.active").removeClass("active");
Then the DOM dont need to search for any ul, instead it goes directly to the class .active
why don't you try this :
$("#menu").find("ul:first").find(".active").removeClass("active");
$('a[href="/pacmodule/completeglass"]').parent().addClass("active");
you might wanna check this fiddle

Get Text Of Closest Parent H4 Using Jquery

I have several of these html blocks on a page in this structure
<div class="listing">
<h4>Some test Entry here</h4>
<div class="entry clearfix">
<a href="#" class="btn">
Text Here
</a>
</div>
</div>
I have the click event on the '.entry .btn' which is firing fine. But I want to get the inner text of the 'H4 a' within the same listing block as the btn I clicked. I have tried the following but just cannot seem to get the H4 text.
var getTitle = $(this).parents("h4").first();
alert(getTitle.html());
I have also tried closest() but still cannot get the H4? Any ideas?
closest & parents looks for ancestors. But, h4 is in another children of parent .listing.
Try:
var getTitle = $(this).closest('.listing').find("h4").first();
Firstly You need to traverse upwards in the DOM structure to identify the target element using .parent() or .parents() functions.
For your requirement you dont need the immediate parent hence .parent() is of no use instead you need to use .parents() to get all the ancestors in the DOM and refer the one with class selector .listing & finally traverse inward to find the target element h4.
JS CODE:
$('.btn').on('click',function(){
alert($(this).parents('.listing').find('h4').html());
});
Live Demo # JSFIDDLE
Happy Coding :)
use prev function in jquery
var getTitle = $(this).prev().find("h4").first();
alert(getTitle.html());

find number of nodes between two elements with jquery?

I'm having a little trouble figuring out a fast way to accomplish a (seemingly) simple task. Say I have the following html:
<ul>
<li>One</li>
<li>Two</li>
<li id='parent'>
<ul>
<li>Three</li>
<li>
<ul>
<li>Four</li>
<li id='child'>Five</li>
</ul>
</li>
<li>Six</li>
</ul>
</li>
</ul>
And have the following two elements:
var child = $("#child");
var parent = $("#parent");
In this example, it's clear that:
child.parent().parent().parent().parent();
will be the same node as 'parent'. But the list I'm traversing is variable size, so I need to find a way to find out how many '.parent()'s I'll need to go through to get to that parent node. I always know where child and parent are, I just don't know how many 'layers' there are in between.
Is there any built in jQuery method to do something like this, or is my best bet a recursive function that gets the parent, checks if the parent is my desired node, and if not calls itself on its parent?
Edit: I may not have explained myself clearly enough. My problem isn't getting TO the parent, my problem is finding out how many nodes are between the child and parent. In my example above, there are 3 nodes in between child and parent. That's the data I need to find.
If you just want to get to the parent, do this:
child.parents("#parent");
That's easier than doing:
child.parent().parent().parent();
Or is there some other reason you need to know the number?
A simple loop could do it:
var node = child[0];
var depth = 0;
while (node.id != 'parent') {
node = node.parentNode;
depth++;
}
Try the closest() function
http://docs.jquery.com/Traversing/closest#expr
This will give you the total number of ul parents:
var numofuls = $(this).parents('ul').length;

Categories