This question already has answers here:
Removing HTMLCollection elements from the DOM
(5 answers)
Closed 8 years ago.
i have a link and i would like to remove it using javascript
here's what i have so far
test
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; ++i) {
if (a[i].innerText === 'test') {
a.remove();
}
}
this will fail.
Don't do it this way. document.getElementsByTagName('a') returns live collection, so loop in reverse order. So try
var aColl = document.getElementsByTagName('a');
for (var i = aColl.length-1; i >= 0; i--) { //loop from reverese order, so that removed item doesn't affect
var thisNode = aColl[i];
if (thisNode.innerHTML === 'test') {
thisNode.parentNode.removeChild(thisNode );
}
}
Fiddle
If you do it for (var i = 0, len = a.length; i < len; i++) { then you end up removing only half of it, since each removal will update the NodeCollection in a and you will end up losing the elements at higher index and your check will fail.
Related
My query is simple :
How to remove all elements except last one with same document.querySelectorAll(".someClass") using only javascript without jQuery.
I can do it with jQuery with only one line like this:
$('.someClass').not(':last(2)').remove();
But I want to do it with pure JavaScript; how can I do that?
Any idea?
I tried this code :
var lists = document.querySelectorAll(".someClass");
for(var i = 1; i < lists.length; i++) {
lists[i].parentElement.removeChild(lists[i]);
}
But it removes all elements except the first one. But I want to keep the last one.
This will remove all but the last element from your nodeList
EDIT:
const elems = Array.from(document.querySelectorAll(".someClass"))
elems.pop()
elems.map(node => node.parentNode.removeChild(node))
var lists = document.querySelectorAll(".someClass");
for(var i = 0; i < lists.length -1; i++) {
lists[i].parentElement.removeChild(lists[i]);
}
Try using this.
var lists = document.querySelectorAll(".someClass");
for(var i = 1; i < lists.length; i++) {
if (i !== lists.length - 1) lists[i].parentElement.removeChild(lists[i]);
}
You can perform the above action on every item in the array except for the last one (the last index is array.length - 1 since the first index is 0.
You were close:
let endIndex = 1 // how many you want to delete
var lists = document.querySelectorAll(".someClass");
for(var i = 0; i < lists.length - 1 - endIndex; i++) {
lists[i].parentElement.removeChild(lists[i]);
}
Stop just before the last one:
var lists = document.querySelectorAll(".someClass");
for(var i = 1; i < lists.length - 1; i++) {
// ^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
lists[i].parentElement.removeChild(lists[i]);
}
Or alternatively, in all vaguely-modern browsers:
const lists = Array.prototype.slice.call(
document.querySelectorAll(".someClass"),
0, -1
);
for (const list of lists) {
list.remove();
}
That uses the slice method from Array.prototype to grab all of the entries from the NodeList returned by querySelectorAll except the last one, then loops over that result removing those elements.
Try with this:
$("#parent_id").children(":not(#id_n)").remove();
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Returning only certain properties from an array of objects in Javascript [duplicate]
(5 answers)
Javascript Array of objects get single value [duplicate]
(3 answers)
Construct an array of elements from an array of objects? [duplicate]
(2 answers)
Closed 4 years ago.
How to save javascript data from a loop to an array?
for (i = 0; i < jsonData.Data.Positions.length; i++) {
var h = jsonData.Data.Positions[i].Oid;
}
Insert the data in the array using push
var arr=[];
for (i = 0; i < jsonData.Data.Positions.length; i++) {
var h = jsonData.Data.Positions[i].Oid;
arr.push(h);
}
var data = [];
for (i = 0; i < jsonData.Data.Positions.length; i++) {
var h = jsonData.Data.Positions[i].Oid;
data.push(h)
}
//OR
var data = jsonData.Data.Positions.map(item => item.Oid);
Your variable jsonData.Data.Positions is probably already an array.
Use .push() method to add values to array.
var h=[];
for (i = 0; i < jsonData.Data.Positions.length; i++) {
h.push(jsonData.Data.Positions[i].Oid);
}
console.log(h);
You can do it within a loop:
var array = []
for (i = 0; i < jsonData.Data.Positions.length; i++) {
array.push(jsonData.Data.Positions[i].Oid);
}
Or in a more functional-way:
var array = jsonData.Data.Positions.map(p => p.Oid)
map instead of for loop
var h = jsonData.Data.Positions.map(function (x) { return x.0id });
This question already has answers here:
$.each() vs for() loop - and performance
(6 answers)
Closed 5 years ago.
I want to replace my
$("p").each(function(i)
with
for (var i = 0, len = $('p').length; i < len; i++) {
$('p')[i];
}
for faster performance. I want to keep the same switch statement. How do i do it? I'm new with javascript and also my switch statement is alot longer , but i shorten it so you guys can see it better. My problem is $(this) . Thanks in advance.
for (var i = 0, len = $("p").length; i < len; i++) {
$("p")[i];
}
$("p").each(function(i) {
switch(window.localStorage['kgenfavred' + i])
{
case 'yred':
$(this).addClass("favoritesred");
$(this).removeClass("favoritesyellow");
break;
}
});
var paragraphs = document.getElementsByTagName('p');
for (var p = 0; p < paragraphs.length; p++) {
switch(window.localStorage['kgenfavred' + p]) {
case 'yred':
paragraphs[p].classList.add('favoritesred');
paragraphs[p].classList.remove('favoritesyellow');
break;
}
}
JSFiddle example
Your current approach is likely to be slower, since you've added a DOM lookup on each iteration. If you really want to convert to a for loop, capture your element set first, then iterate over it - accessing the current element with .eq(index):
var $p = $('p');
for (var i = 0, len = $p.length; i < len; i++) {
// get jquery element
console.log($p.eq(i));
// or get DOM node
console.log($p.get(i));
}
As #Kinduser pointed out, it probably would be fastest/easiest just to cut jQuery out of the picture altogether:
var p = document.querySelectorAll('p');
for (var i = 0; i < p.length; i++) {
console.log(p[i]);
}
Or newer:
document.querySelectorAll('p').forEach((element) => {
console.log(element);
});
This would be incorrect. You can use .each() method of jQuery:
var $ps = $(document).find('p');
for (var i=0; i<$ps.length; i++)
{
let temp = $ps[i]; /// this is a dom element and if you want use jQuery methods, you need to use a selector over it;
let $temp = $(temp); /// this is jQuery element
/// Do whatever you want here
}
This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 6 years ago.
I tried something like:
var diff = $(array1).not(array2).get();
console.log(diff); // store the difference
And replace .not() with .is() but that didn't work..which generated an error. It only stored the difference, but I want only the same values stored in a new array. How do I do that in jQuery regardless if it's length size in both arrays?
var array1 = ['a','b','c','d','e','f','g'];
var array2 = ['c', 'b'];
var sameValArr = [];
// TODO:
// 1. compare the two arrays if there's any matching values in both
// 2. if yes, store the matching value in a new array; if no, do nothing
// 3. check the new array if it isn't empty
// 4. if empty, hide the video; if not empty do nothing (show video)
for(var i = 0; i < array1.length; i++)
{
for(var j = 0; j < array2.length; j++)
{
if(array1.indexOf([i]) === array2.indexOf([j]))
{
sameValArr.push(array1[i]);
console.log("sameValArr: ", sameValArr);
}
}
}
The answer provided to this question using indexOf() method didn't work.
for(var i=0; i< array1.length; i++)
{
for(var j=0; j< array2.length; j++)
{
if(array1[i] === array2[j])
sameValArr.push(array1[i]);
}
{
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Simplest code for array intersection in javascript
How to merge two arrays in Javascript
There are three arrays:
var items = Array(523,3452,334,31,5346);
var items_used = Array(3452,31,4123);
var items_new = Array();
First one is general, second is the items currenly in use. Third one includes all the items from the first array, witch are not mentioned in second.
How do I remove from the first array items, witch are used in second, and write the result to the third array?
We should get items_new = Array(523, 334, 5346). 3452 and 31 are removed, because they are mentioned in second array.
You could do this:
var items = Array(523,3452,334,31,5346);
var items_used = Array(3452,31,4123);
var items_compared = Array();
$.each(items, function(i, val){
if($.inArray(val, items_used) < 0)
items_compared.push(val);
});
That's it
Why not a simple for loop?
for(var j = 0; j < items.length; j++)
{
var found = false;
for(var k = 0; k < items_used.length; k++)
{
if(items_used[k] == items[j])
{
found = true;
break;
}
}
if(!found)
items_compared.push(items[j]);
}
As a faster solution maybe :
var j, itemsHash = {};
for (j = 0; j < items.length; j++) {
itemsHash[items[j]] = true;
}
for (j = 0; j < itemsUsed.length; j++) {
itemsHash[itemsUsed[j]] = false;
}
for (j in itemsHash) {
if (itemsHash[j]) {
itemsCompared.push(j);
}
}
runs in O(n) time, with a little more memory.
Basically I would make the third have all elements in the first, then loop through the second array removing all of those elements found in the first.
var items_compared = items;
for(int i = 0; i < items_used.length; ++i)
{
var indx = $.inArray(items_used[i], items_compared);
if(indx != -1)
items_compared.splice(indx, 1);
}