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>
Related
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
Which is the best way to traverse through a <ul> list and add a particual text to each <li> ??? Can i do with with a FOR loop like:
for (i=0; i<$('li').length; i++){
('li').eq(i).text(bla bla)
}
You can simply use text() with callback it will iterate
$('li').text(function(i,v){
// i - index of the element and v - old value
return 'bla bla';
// -------^---- new value to update
});
For example :
var con = ["first", "second", "third", "fourth"];
$('li').text(function(i) {
return con[i];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
In your example you dont need any loop whatsoever
$('li').text('blah blah')
will already update every li with the text
Yes it is. While each() has a simple syntax it is worse performance wise. Nevertheless you should select a DOM object one single time and then use the reference if nothing has changed withing the DOM. Otherwise jQuery will search the DOM multiply times every single loop
var elements = $('li');
for (var i = 0; i < elements.length; i++){
elements.eq(i).text(bla bla)
}
Nope, this is too heavy. Bare in mind that every time you call $('li'), jQuery looks for all <li> elements in the page and generates a collection out of them. As such, jQuery has a wonderful feature of method chaining and iterating, that will help to keep code fast. For iterating elements in a collection you can use a special .each method:
$('li').each(function(i) {
$(this).text('element #' + i);
});
Or if you simply need to set the same text to all matching elements in a collection, use .text method applied to a selected jQuery object:
$('li').text('same text');
I'm trying to identify a li element from a group of li inside of div
<div id="group">
<li></li>
<li></li>
<li></li>
</div>
its quite simple tho, i could give each li an unique id and this problem would be over. like
var listItem1,2,3 = document.getElementById('liItem1,2,3') etc
listItem1,2,3.addEventListener('click',function);
this might be handy when it comes to 1,2 or 3 elements but this is all static and when it start to scale its not possible anymore, Instead im trying to make use of NodeList.
var nodeList = document.getElementById('group').getElementsByTagName('li');
now i will have a NodeList with li 0, li 1, li 2
the problem comes now becouse i don´t know how to trace which li is being clicked.
nodeList.addEventListener('click',function);
wont work here becouse it dosent know which one is being clicked at here.
nodeList[0].addEventListener('click',function);
is the same solution as above. How can i trace which of the li is being clicked at? only plain/raw javascript
To find the index of an element in response to an event, I'd suggest delegating the event-handling to an ancestor (rather than individually binding an event-handler to multiple child-elements):
// 'event' is passed in automagically (in non IE browsers, haven't tested IE):
function getIndexFrom(event){
// event.target is the element upon which the event was triggered:
var clicked = event.target,
// finding all the children of the parent of the clicked-element
// (could use 'this.children', as 'this' will be the 'ul' in this demo):
children = clicked.parentNode.children;
// iterating over those child elements:
for (var i = 0, len = children.length; i < len; i++){
// if the clicked element is the current element:
if (children[i] === clicked){
console.log('index is: ' + i)
// we return 'i' as the index:
return i;
}
}
// this shouldn't happen, assuming we're looking at the right group
// of elements, but it's there as an in-case and for debugging:
return false;
}
document.getElementById('group').addEventListener('click', getIndexFrom);
JS Fiddle demo.
References:
EventTarget.addEventListener().
for... loop.
ParentNode.children.
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");
Is it possible using JavaScript to dynamically remove just a few li elements from a ul, given the id's of the li elements?
UPDATE about the actual issue:
I've the following list.
<ul id="attributes" data-role="listview">
<li id="attrib01">Attribute1</li>
<li id="attrib02">Attribute2</li>
<li id="attrib03">Attribute3</li>
<li id="attrib04">Attribute4</li>
<li id="attrib05">Attribute5</li>
</ul>
After a ajax request/response, if a particular attribute is "undefined", I want to remove it from the list.
if(typeof data.attrib1 === "undefined")
$("#attrib01").remove();
I've made sure I'm receiving the correct ajax response. So, the problem now is, that when I remove attrib4, attrib[1-3] are being removed as well. Any idea why this might be happening?
Try
var elem = document.getElementById('id');
elem.parentNode.removeChild(elem);
If you get the element then find its parent then remove the element. from the parent as follows:
element = document.getElementById("element-id");
element.parentNode.removeChild(element);
It is necessary to go through the parent so this is unavoidable.
$('#id').remove() is the correct way to remove a single element. Note that element IDs must be unique in html, and that invocation must be wrapped in a DOM ready function.
This is a working example based on your html. It loops through all the list-items and removes the one whose id is not present in the data object:
var data = {
attrib01: "Number 1",
attrib02: "Number 2",
attrib04: "Number 4"
};
$(document).ready(function() {
$("ul > li").each(function() {
alert(this.id in data); //check if value is defined
if(!(this.id in data)) {
$(this).remove();
// This also works:
//$('#'+this.id).remove();
}
});
});
It is also possible to target and remove only a single element (Demo) by simply doing:
$(document).ready(function() {
$("#attrib04").remove();
});
Be careful with your IDs -- they must match exactly. attrib04 != attrib4
This will make the li elements invisible:
document.getElementById("id_here").style.visibility = "hidden";
Disclaimer: they will still be in the DOM
To remove elements from the DOM use JQuery's .remove() method:
$("#id_here").remove();
http://api.jquery.com/remove/