How to remove the last element from JQuery array? - javascript

I want to select some DOM elements into a clone object then I want to remove the last item. After trying it in Chrome console I see that clone's length does not decrease.
Example from Chrome console:
crumbs = $("span",$("div[style='width:390px;background-color:white;'")[0]).clone();
jQuery.fn.jQuery.init[114]
crumbs.last().remove()
[​…​​]
crumbs.length
114
As you see, length is still 114 elements. What am I missing?

crumbs.last().remove() removes the last matched element from the DOM, it doesn't remove it from the jQuery object.
To remove an element from the jQuery object¹ use slice:
var withoutLastOne = crumbs.slice(0, -1);
¹ Actually this will create a new object that matches one less element instead of modifying your existing object. You will usually not care about the distinction, but should be aware of it.

To remove last element from the array you can use below code too.
var arr = ["item1", "item2", "item3", "item4"];
arr.pop();
Demo

As people said, .remove() removes the element from the DOM. Another option than using slice on the final result is to use jquery's filtering before cloning the element:
crumbs = $("span",$("div[style='width:390px;background-color:white;'")[0]).not(':last').clone();

Related

insertBefore function for arrays and/or HTMLCollections?

Does there exist a function in vanilla JavaScript or jQuery that operates similarly to Node.insertBefore(), but for arrays and/or HTMLCollections?
An example could look something like:
var list = document.getElementsByClassName("stuff");
var nodeToMove = list[0];
var otherNode = list[4];
list.insertBefore(nodeToMove, otherNode);
Basically I'm trying to perform insertBefore() without manipulating the actual DOM, as I want the changes to only be applied to the DOM under certain conditions. If those conditions are met, then I would perform insertBefore() on the actual nodes.
To clarify, I'm looking for a function that would insert an element before a target element at a given index in an array, not necessarily at a given index. Examples I've seen using splice() usually insert an element at a given index, which sometimes puts the element before the target element, and sometimes after, depending on where the element to be moved originally was in the array. I'm looking for something that would reliably put the element to be moved before the target element.
HTMLCollection does not have an insertBefore method. jQuery can apply any jQuery methods both to a single element being selected, as well as many.
https://api.jquery.com/insertBefore/
There is no single method to do this in one step, but there doesn't need to be. If you convert the collection to an Array, you can call the Array.prototype.splice() method to achieve the same result.
Here's an example:
let ary = [1,2,3,4,5];
// Swap 2 and 3
// Start at the 3rd item and remove one item (3).
// Store the removed item
let removed = ary.splice(2,1);
// Start at the second item, don't remove anything, insert the removed
// item at that position
ary.splice(1,null,removed[0]);
// Log the result
console.log(ary);
And, with that knowledge, you can create your own more easily callable function:
let ary = [1,2,3,4,5];
function insertBefore(ary, newItem, target){
ary.splice(target,null,newItem);
}
// Insert 999 before the 3rd array item
insertBefore(ary,999,2)
console.log(ary);
You need to get the index you want, then use Array.splice.
Myself I would do something like this :
const myArr = ['Aurore', 'Dimitri', 'Alban', 'Frédéric'];
const insertBeforeThis = 'Alban';
const eltToInsert = 'Laura';
const index = myArr.findIndex(name => name === insertBeforeThis);
myArr.splice(index, 0, eltToInsert);
Please feel free to try it out in your browser's console. Note i used const for my array, as it fixes the type of the variable as an array but allow me to manipulate it.
MDN: Array.prototype.findIndex()
stackoverflow: How to insert an item into an array at a specific index (JavaScript)?
Have a happy coding time!

Why do getElementsByTagName() always returns an array?

Why is it that if I have only one h1 element in the document, I still have to use the index to access it?
Like the following doesn't work.
document.getElementsByTagName('h1').innerHTML = "SHUSHAN";
but if I do
document.getElementsByTagName('h1')[0].innerHTML = "SHUSHAN";
It does work.
Even though I only have one h1, why do I have to specify?
Short answer: This is so that you can have some sanity.
If you don't know whether you will get a single element or a collection of elements, you would have to write defensive, type-checking (stupid) code like this
let foo = document.getElementsByTagName('h1')
if (foo instanceof HTMLCollection)
// do something with all elements
else
// do something with just one element
It makes way more sense for the function to always return a known type, an HTMLCollection of HTMLElement objects
If you only care about getting the first element, you can use destructuring assignment
let [first] = document.getElementsByTagName('h1')
console.log(first) // outputs just the first h1
This is fine because the assignment clearly shows that it's expecting an array (or array-like) of elements but only cares about assigning an identifier to the first value
You should also be aware of the newer document.querySelector and document.querySelectorAll functions …
document.querySelector will select at most one element from the document or returnnull
document.querySelectorAll will always return an HTMLCollection, but may be empty if no elements match the selector.
Here's how I'd write your code in 2017
setTimeout($ => {
// get the element to change
let elem = document.querySelector('h1')
// update the text of the element
elem.textContent = 'SHUSHAN'
}, 3000)
<h1>wait 3 seconds ...</h1>
getElementsByTagName - the method name itself implies that it will return multiple elements - i.e. an array. The method always returns an array, with the length equal to the number of matching elements. As such you must always access the elements by the index of the element in the array.
Arrays must be accessed by index regardless of how many values it holds. Do some reading on array data types to get a better understanding of the concept.
The point is that getElementsByTagName always returns a HTMLCollection of elements, which works mostly as an array. If there is only one element in this collection, then its index is 0.
This is the reason why you must specify the index, even if there is only one element in the document.
Click here or here to see more documentation about this.

Get the last item from node list without using .length

The following command
document.querySelectorAll('#divConfirm table')[1].querySelectorAll('tr')
gives a node list with 3 tablerow (tr) elements in it. If I know the list size, I can access the last element via.item(2).
Is there a way to get the last element directly without resorting to .length first?
There's at least one way
var els = document.querySelectorAll('#divConfirm table')[1].querySelectorAll('tr');
var last = [].slice.call(els).pop();
but, the following statement
But if I do not know the length prior to running the script
makes no sense, you already have the collection of elements, so you would always know the length
var els = document.querySelectorAll('#divConfirm table')[1].querySelectorAll('tr');
var last = els[els.length - 1];
Another option as the8472's answer suggests would be
document.querySelector('#divConfirm table:nth-child(2) tr:last-child');
Since NodeList doesn't have a pop method.
Using the spread syntax in a new array, then pop() to get the last element.
This basically copy the Nodelist as a regular array, thus the pop() and other array methods become available.
console.log(
// Last elem with pop()
[...document.querySelectorAll("div")].pop()
)
console.log(
// 2nd elem
[...document.querySelectorAll("div")].slice(1)[0]
)
console.log(
// By index :) just in case
document.querySelectorAll("div")[0]
)
<div>The sun</div>
<div>is</div>
<div>shinning</div>
depending on circumstances this may work: document.querySelector('#divConfirm table tr:last-of-type')
You can transform the NodeList into an Array. Then can use array.pop(). It return the last item BUT remove it to the array!
const elementsArray = Array.from(elements);
elementsArray.pop()

Javascript splice is removing everything but the element requested

I have a pretty simple script that takes content from an input box, makes an array out of it, removes a desired element, and spits back the text.
I'm trying to use "splice()" to remove the item but it removes everything BUT that one item:
var listOfTitles = $('.title-list').val();
var arrayOfTitles = listOfTitles.split(',');
var updatedTitles = arrayOfTitles.splice(2,1);
$('.title-list').val(updatedTitles.join());
for example if I have this:
test1,test2,test3,test4
I can turn it into an array. I want to removed "test3" and output "test1,test2,test4". The problem is, it's returning "test3" not removing it.
jsfiddle of what's happening: http://jsfiddle.net/C95kN/
Splice() modifies the array in place and returns an array with the elements you remove.
What you want is arrayOfTitles not updatedTitles
See working fiddle: http://jsfiddle.net/C95kN/1/
splice changes the passed array and returns the removed elements. Simply do
arrayOfTitles.splice(2,1);
$('.title-list').val(arrayOfTitles.join());
Note that I supposed the slice instead of splice was a typo.

Javascript "shift" versus "splice" - are these statements equal?

I just want to confirm if the following two Javascript statements produces the same results, as it seems to me:
First:
var element = my_array.splice(0,1)[0];
Second:
var element = my_array.shift();
I want to substitute the first by the second, in my own code, to improve readability. Can I do this?
They will have the same effect, yes. splice(0, 1) will remove the first element from my_array and return a new array containing that element. shift will do the same, but return the element itself, not an array.
shift is more readable (in my opinion) and is also significantly faster (in Chrome at least):
Both lines of code remove the first element from the array, and return the removed element, they are both supported in all major browsers.
You should use the second one, and the code will be more readable indeed.
shift returns the element that was removed, splice returns an array of elements that were removed.
that being said, the two statements do the same thing and i would agree that the second is more readable.
splice will return as an array but not remove data from the object instead make a copy
shift just give one data from front and also remove from object
For example,
const object = {1}
object.slice(); // return [{1}]
//object will be : {1}
object.shift(); // return {1}
//object will be : {} as shift remove the front data

Categories

Resources