JavaScript remove all elements with name - javascript

I am trying to use JavaScript to remove all the elements with a certian name, but it is only removing the first one.
My code is:
var ele= document.getElementsByName("javascriptaudio");
for(var i=0;i<ele.length;i++)
{
ele[i].parentNode.removeChild(ele[i]);
}
Can anyone tell me what is wrong?
Thanks

I don't have enough rep to comment on Álvaro G. Vicario. The reason that it works is that the element is removed from ele when it is removed from the DOM. Weird.
The following code should work equally well:
var ele= document.getElementsByName("javascriptaudio");
len = ele.length;
parentNode = ele[0].parentNode;
for(var i=0; i<len; i++)
{
parentNode.removeChild(ele[0]);
}

Try removing them backwards:
var ele = document.getElementsByName("javascriptaudio");
for(var i=ele.length-1;i>=0;i--)
{
ele[i].parentNode.removeChild(ele[i]);
}
The problem is that removing elements from ele shifts indexes: if you have 5 items (0 to 4) and remove item 0 you then have 4 items ranging from 0 to 3 (4 becomes 3, 3 becomes 2, etc.); you should then remove item 0 but your i variable has already incremented to 1.

you need to save length of array outside the loop because it is evaluated with each pass if you place it inside loop criteria. That way you will have correct amount of iterations. Furthermore you need to delete first item in loop each time because with each pass you lose 1 item so you will be outside of range at the end of process.
var ele = document.getElementsByName("javascriptaudio");
var elementsCount = ele.length;
for(var i=0;i<ele.length;i++){
ele[0].parentNode.removeChild(ele[0]);
}

Try the following jQuery code:
$("[name=javascriptaudio]").remove();

Related

Include duplicates in for and if loop of array as count number is too small

I'm new to javascript so any help would be greatly appreciated.
What I'm trying to do is cycle through every element in the array and count the number of times the value of an element matches a given condition (even if the value is duplicated).
function loaddata(xml) {
var count = 0;
var i;
var xmlDoc = xml.responseXML;
var z = xmlDoc.getElementsByTagName("group");
if (value1 <= value2) {
for (i = 0; i < (0 + z.length); i++) {
if (z[i].getElementsByTagName("name")[0].childNodes[0].nodeValue == "John") {
count++;
}
}
}
$('#count1').html(count);
};
The count value outputted is too small. I believe the reason for this that the for loop isn't iterating through all elements in the array. When I remove the second if loop and output the count for just the for loop this value is also too small. I believe that the for loop isn't searching through the duplicate elements of the array (i.e. it is ignoring them so that they aren't then fed into the second if loop). Is it possible to specify that the for loop include duplicates?
Do a console.log(z[i].getElementsByTagName("name")) and open your browser's console, and see if that array has data in it.
Then console.log(z[i].getElementsByTagName("name")[0].childNodes) and make sure you have nodes in it.
Also, do you have many <group></group> tags? Because that's what you are selecting with var z = xmlDoc.getElementsByTagName("group");
I hope that helps,

JavaScript - Looping array less than I should

I'm trying to loop an array which contains a list of elements returned by ClassName, but I can't loop all of them, because of the next situation:
var list = document.getElementsByClassName('class');
for (var i = 0; i < list.length; i++) {
var theClass = list[i].className; //once got list[i].
theClass = theClass.replace('class', '');
list[i].className = theClass; //twice got list[i].
}
If the size of the list is = 4, I just can loop two times, because I'm getting twice each position per loop. Do you know what I can do and why it happens? Thank you.
The data structure returned by getElementsByClassName is Array-like and dynamic based on the DOM. Once you replace the class on the list item in question, you end up losing an item per iteration.
To fix this, you can take a copy of the returned values first before operating on them, or work backwards.
Take a copy:
var list = document.getElementByClassName('class')
var realList = []
Array.prototype.push.apply(realList, list)
for (var i = 0; i < realList.length; i++) {
// do changes as you have already
}
Working backwards:
var list = document.getElementsByClassName('class')
for (i=list.length - 1; i >= 0; i--) {
// do changes to list[i]
}
Another poster briefly mentioned a while loop which also works, but then their answer disappeared (I don't want to take credit for this!):
var list = document.getElementsByClassName('class')
while (list.length != 0) {
// do changes to list[0]
}
If you write out what happens in your initial code, you can see the problem more clearly:
Iteration 1: i=0, list=[a,b,c,d], length = 4, list[i]=a
Iteration 2: i=1, list=[b,c,d], length = 3, list[i]=c
Before Iteration 3: list=[b,d], i=2, length = 2, loop breaks
Now writing out what happens when using the reverse loop:
Iteration 1: i=3, list=[a,b,c,d], length = 4, list[i]=d
Iteration 2: i=2, list=[a,b,c], length = 3, list[i]=c
Iteration 3: i=1, list=[a,b], length = 2, list[i]=b
Iteration 4: i=0, list=[a], length = 1, list[i]=a
All these solutions are variations on this solution of avoiding using i to reference the middle parts of the array-like result value of getElementsByClassName so that the dynamic nature of it is dealt with.

Get last 4 characters of every element of array in JavaScript

I would be surprised if this hasn't been asked in the past. I was unable to find something that works. I have an array of strings and I would like to create a new array with only the last 4 characters of each of the elements. The code is below. What do I need to change to make it work?
for(i=0; i<userScanDataObjects.length;i++){
// if statement used to select every alternative element from the array as th rows are duplicated
if (i%2 !==0){
deviceID_raw.push(userScanDataObjects[i].deviceID.value);
deviceID.push(deviceID_raw[i].substring(5,8));
}
['11114444', '22224444'].map(function(string) { return string.substring(string.length - 4, string.length) })
You can use Array.map depending on your targeted browser support/polyfills. And you can do the following:
for( var i = 0; i < array.length; ++ i ) {
array[i] = array[i].substr(-4);
}

Multiply an element by a number and insert using jQuery

I'm wondering if you can multiply an element using jQuery a number of times and insert it using .html()?
I am building my own slider which might help put things in context...
I am getting a number of times an element is used, which is stored in a var called eachSlideCount. So for example, this might output 10.
Then what I want to do is create a <span></span> for each of these (so 10 spans) and insert this into a div to generate a pager.
$this.next('.project-slider-count').html('<span></span>')
Is there anyway to muliply this span by the eachSlideCount number and then add to the .project-slider-count element?
I got this far... but clearly missing something...
var eachSlideCount = $this.find('.other-slides').length;
var eachSlideTotal = ($this.next('.project-slider-count').html('<span></span>')) * eachSlideCount;
$('.project-slider-count').html(eachSlideTotal);
Thanks in advance
Multiplication can only be done on numbers. If you want to repeat something, write a loop:
var span = '';
for (var i = 0; i < eachSlideCount; i++) {
span += '<span></span>';
}
$this.next('.projectslider-count').html(span);
In JavaScript, you can execute a for loop. For example, in the following:
var count = 10;
for (var i=0; i<count; i++) {
// Code
}
The body of the loop would be executed 10 times.
In jQuery, you can append a new HTML element inside an existing element using the append() method. For example, the following will add <span> elements in a loop:
var container = $("#container");
var count = 10;
for (var i=0; i<count; i++) {
container.append("<span>");
}
This is illustrated in a jsFiddle.

Problem with dropdownbox length

I'm creating a javascript method that populates lists depending on a radio button selected previously. As it depends on animals or plants to populate it, my problem comes when I have to populate it after it's already been populated. I mean, the plants dropdownlist has 88 elements, and the animals is 888, when I try to come back from animals to plants, I get some of the animals. I know that my controller method is working properly because it returns the values I select, so the problem is the javascript method. Here is the code:
if(selector == "sOrder")
alert(document.getElementById(selector).options.length);
for (i = 0; i < document.getElementById(selector).options.length; i++) {
document.getElementById(selector).remove(i);
}
if (selector == "sOrder")
alert(document.getElementById(selector).options.length);
document.getElementById(selector).options[0] = new Option("-select-", "0", true, true);
for (i = 1; i <= data.length; i++) {
document.getElementById(selector).options[i] = new Option(data[i - 1].taxName, data[i - 1].taxRecID);}
Here is the strange thing, when I enter the method I try to erase all the elements of the dropdownlist in order to populate it afterwards. As sOrder is the same selector I had previously selected, I get the elements, the thing is that the first alert I get the proper result, 888, but in the second alert, I should get a 0 right? It shows 444, so when I populate it again it just overrides the first 88 plants and then animals till 444. What am I doing wrong?
Thank you all in advance,
Victor
Essentially you are removing from beginning to the end of the list by using the index, but as you do the index of each consecutive item gets decreased. If you remove from the end to the beginning, the indexes remain the same and you can remove them by index.
Replace
for (i = 0; i < document.getElementById(selector).options.length; i++) {
document.getElementById(selector).remove(i);
}
With
for (i = document.getElementById(selector).options.length -1; i > 0 ; i--) {
document.getElementById(selector).remove(i);
}
A simpler way of removing all items from a select box might be to use:
document.getElementById(selector).innerHTML="";
This would yank the html inside the select. (note I've only tested this in Firefox 3.6.2 but believe this should work in most modern browsers)
I think that in the remove loop there is an error
if(selector == "sOrder")
alert(document.getElementById(selector).options.length);
for (i = 0; i <
document.getElementById(selector).options.length;
i++) {
document.getElementById(selector).remove(i);
}
infact while you're removing elements, document.getElementById(selector).options.length changes.
so during the first iteration you have length=888, then you remove an element
during the second iteration you have length=887 (and i=1) etc.
during the 444th iteration, you have i=443 and length=444 and the loop exit after removing the 444th element.

Categories

Resources