Selecting a last child in javascript - javascript

I have a handle on an Un-ordered List (for my example i will call the handle Var1) and would like to be able to assign its last li to a variable. I tried Lastli = var1.lastChild the only method I figured would work but it didn't. I can't seem to find a answer to this using only Javascript not jQuery any help is appreciated.

You can select the parent element and use the lastChild property.
var container = document.getElementsByTagName("ul")[0];
var lastchild = container.lastChild;
Or you select all the items into an array and get the last item. Here is a quick example:
var items = document.querySelectorAll("li");
var lastchild = items[items.length-1];

you can select all 'li' and take the last one. Something like:
var myLi = document.getElementsByTagName('li');
var lastLi = myLi[myLi.length-1];

Lets consider an example
<ul >
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
To get the last child of the list you can simply make use of queryselector
document.querySelector('li:last-child'); //this will return Milk which is the last child of the list
document.querySelector('li:first-child') OR document.querySelector('li'); //both will give you the first child of the list
Suppose you want the n-th child for that you can use the following syntax:
document.querySelector('li:nth-child(2)'); //it will return the second child (here Tea)
If you want all the list item in the given list:
document.getElementsByTagName('li') //(Will return the whole list)here i am using tagname. It can be also applied on classname or element id

Try this: .childNodes[childNodes.length - 1]

either ulReference.children[ulReference.children.length -1] or ulReference.childNodes[ulReference.childNodes.length -1]. The difference between the two can be found here

The simplest way is to use the document.querySelector and use the :last-child to get it.
Exemple:
const list = document.querySelector("li:last-child");

Related

Javascript how to append an element to div with specific class

I have some <div>s where I want to append some data to a child div with a specific class but I'm not sure how to do that:
Here is my JS code:
let items = document.querySelectorAll(".item");
items.forEach(function (item) {
let textnode = document.createElement('p');
textnode.innerHTML = 'some text';
item.appendChild(textnode);
});
This actually works, bu it only appends the "textnode"-element to the existing elements.
When I try:
document.getElementsByClassName('left').appendChild(textnode);
It doesn't work.
Here is a JSFIDDLE
EDIT
I want to append the data to the .left element
It seems you want to append an element to .left descendant of item elements. If this is the case, you can use the querySelector instead of getElementsByClassName:
item.querySelector('.left').appendChild(textnode);
Note that above code calls the querySelector method as a member of item (instance of HTMLDivElement interface).
getElementsByClassName returns multiple elements. Class names are not unique. Therefore you first need to select an element in that list.
var textnode = document.createTextNode("Test");
var node = document.getElementsByClassName('left');
node[0].appendChild(textnode);
<div class="left"></div>
getElementsByClassName returns the array of elements. So u need to use the index for that.
let x = document.getElementsByClassName('left')
x[0].appendChild(textnode)
This is working.
I have updated the code in your fiddle. Please check out

How to get the first <ul> element from a document in JavaScript?

First of all, sorry If it isn't clear in the beginning, but let me explain: I want to get the div with a class and the first <ul> from a document (I'm using blogger). I already have a JS that picks up the first image and creates a thumbnail like this:
//<![CDATA[
function bp_thumbnail_resize(image_url,post_title)
{
var show_default_thumbnail=true;
if(show_default_thumbnail == true && image_url == "") image_url= default_thumbnail;
image_tag='<img src="'+image_url.replace('/s72-c/','/')+'" class="postimg" alt="'+post_title+'"/>';
if(image_url!="") return image_tag; else return "";
}
//]]>
and below,
document.write(bp_thumbnail_resize("<data:post.thumbnailUrl/>","<data:post.title/>"));
Now the structure that I want (because I cannot display the full post in the homepage due to the size of other elements):
<div class="Title1">
<h3>Title</h3>
</div>
<ul>
<li>DESCRIPTION1</li>
<li>DESCRIPTION2</li>
</ul>
There are number of ways in which you can do that. Few are
var firstUL = document.getElementsByTagName('ul')[0];
var firstUL = document.querySelector("ul");
If you also have Jquery in use
$( "ul" ).first();
or
$("ul:first")
How to get the first element from a document in JavaScript?
You could try something as simple as:
var firstUlElement = document.getElementsByTagName('ul')[0];
The getElementsByTageName method of document
returns a live HTMLCollection of elements with the given tag name. The
subtree underneath the specified element is searched, excluding the
element itself. The returned list is live, meaning that it updates
itself with the DOM tree automatically.
as it is stated here.
var firstUl = document.querySelector('ul');

Remove first child in javascript

I'm trying to remove the first li in an ol using the DOM removeChild(). But for some reason it doesn't work.
This is my javascript:
document.getElementById('queue').removeChild(
document.getElementById('queue').childNodes[0]
);
And this is my HTML:
<ol id="queue">
<li>Surprised Kitty (Original)<span class="nodisplay">0Bmhjf0rKe8</span></li></ol>
I tried alerting the childNodes[0], and it returns [Object Text], which seems a bit weird, when I was expecting just the object.
Hope I've been clear.
Try this one-liner:
document.getElementById('queue').removeChild(document.getElementById('queue').getElementsByTagName('li')[0]);
With expanded explanation:
var queue = document.getElementById('queue'); // Get the list whose id is queue.
var elements = queue.getElementsByTagName('li'); // Get HTMLCollection of elements with the li tag name.
queue.removeChild(elements[0]); // Remove the child from queue that is the first li element.
Between the <ol id="queue"> and the <li> tag are spaces and a line break. These make up a text node. The first child of the #queue element is therefore a text node.
You can use the .children property instead of .childNodes, it only considers element nodes, or iterate over all child nodes until you find the first li node, like suggested by dystroy.
remove all lists contained by queue:
var list=document.getElementById('queue');
list.removeChild(list.getElementsByTagName('li')[0]);
Child nodes aren't just the elements you think about but also the text nodes. You can iterate over the nodes and remove the first LI.
var p = document.getElementById('queue');
for (var i=0; i<p.childNodes.length; i++) {
if (p.childNodes[i].tagName=='LI') {
p.removeChild(p.childNodes[i]);
break;
}
}
Demonstration
Note that this is more an explanation than the most practical solution. Javascript has other iteration solutions for you, among them getElementsByTagName, so you may do this :
var p = document.getElementById('queue');
p.removeChild(p.getElementsByTagName('li')[0]);
Demonstration
You can use this single line of code. Which will delete always first child element of the parent.
JavaScript:
document.querySelector('#queue').firstElementChild.remove();
HTML:
<ol id="queue">
<li>
Surprised Kitty (Original)
<span class="nodisplay">0Bmhjf0rKe8</span>
</li>
</ol>

Select Element From List by Index with jQuery

<form id="foo">
<input></input>
<input></input>
<input></input>
</form>
I want to do:
document.getElementById("foo").getElementsByTag("input")[1];
But in jQuery. I want to select a certain object under #foo by an index.
This is my first guess as to how to do this:
$('#foo input[1]').val("BlahBlah");
I think it would be the same in CSS too.
You could do it this way:
$('#foo input').eq(1).val("BlahBlah");
That will give you the second input. If you want the first, change the 1 to a 0. The .eq() function is 0 based.
In jQuery there are a couple of methods defined to select and use elements from a (DOM objects) list.
By using:
var list = $("#foo");
You would capture the entire #foo. If your in for simplicity you could get the children (i.e the input fields) by using var children = list.children(); But if you want something that seems a bit more like findElementsByTag, you could use var children = list.find('input'); (Which ofcourse could be a one liner, but usually you want to re-use the entire list too)
To get the first and last item of a certain list of children there are some predefined functions:
var first = children.first();
var last = children.last();
To find an -nth element you can use http://api.jquery.com/eq/ or http://api.jquery.com/nth-child-selector/
So you would get (note it works just like an array with 0-based index)
var second = children.eq(1);
If you like CSS selector style more you can also try (note the 1-based index)
var second_b = $("#foo input:nth-child(2)");
$('#foo :input').eq(1).val('BlahBlah')
You can use the eq() selector:
$('#foo input:eq(1)').val("BlahBlah");
You can use the eq selector. It receives a zero-based index:
$('#foo input:eq(1)').val('a value');
Use nth-child(n) pseudo class like this ...
$("#foo input:nth-child(0)").val("BlahBlah");
$("#foo input:nth-child(1)").val("BlahBlah");
.
.
.
$("#foo input:nth-child(n)").val("BlahBlah");
I'll say :
$($('#foo input')[1]).val("BlahBlah");

How to select first parent DIV using jQuery?

var classes = $(this).attr('class').split(' '); // this gets the current element classes
var classes = $(this).parent().attr('class').split(' '); // this gets the parent classes.
The parent in the above situation is an ankor.
If I wanted to get the first parent DIV of $(this) what would the code look like?
var classes = $(this).div:parent().attr('class').split(' '); // just a quick try.
* Basically I want to get the classes of the first parent DIV of $(this).
thx
Use .closest() to traverse up the DOM tree up to the specified selector.
var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes.
Use .closest(), which gets the first ancestor element that matches the given selector 'div':
var classes = $(this).closest('div').attr('class').split(' ');
EDIT:
As #Shef noted, .closest() will return the current element if it happens to be a DIV also. To take that into account, use .parent() first:
var classes = $(this).parent().closest('div').attr('class').split(' ');
This gets parent if it is a div. Then it gets class.
var div = $(this).parent("div");
var _class = div.attr("class");
two of the best options are
$(this).parent("div:first")
$(this).parent().closest('div')
and of course you can find the class attr by
$(this).parent("div:first").attr("class")
$(this).parent().closest('div').attr("class")
and for you
$(this).parent("div:first").attr("class").split(' ')
$(this).parent().closest('div').attr("class").split(' ')
Keep it simple!
var classes = $(this).parent('div').attr('class');

Categories

Resources