I want to do multi AddEventListener to specific function, but the result is not what I want.
I get always the last child on the list.
Why?
This is the code:
First section:
<script>
var inside_elm= new Array();
inside_elm[1]="inside_e1";
inside_elm[2]="inside_e2";
inside_elm[3]="inside_e3";
var kk = {
showBox :function(elm){
alert(elm);
document.getElementById(elm).style.display='block';
}
}
function load() {
var e_elm= new Array();
e_elm[1]="e1";
e_elm[2]="e2";
e_elm[3]="e3";
for(var i=1;i<3;i++){
var k=e_elm[i];
alert(inside_elm[i]);
document.getElementById(e_elm[i]).addEventListener('click',function(){kk.showBox(inside_elm[i])},false);
}
}
</script>
The body:
<body onload="load();">
<div id="e1">
e1
<div id="inside_e1" style="display:none;">inside_e1</div>
</div>
<div id="e2">
e2
<div id="inside_e2" style="display:none;">inside_e2</div>
</div>
<div id="e3">
e3
<div id="inside_e3" style="display:none;">inside_e3</div>
</div>
It's basically down to the fact that it doesn't evaluate 'i' until the function executes, by which stage it's set to 3.
What you want to do is use something like the following:
for(var i=1;i<4;i++){
var k=e_elm[i];
alert(inside_elm[i]);
var elm = document.getElementById(e_elm[i]);
elm.inside_elm = inside_elm[i];
elm.addEventListener('click', function(){kk.showBox(this.inside_elm)},false);
}
I think it is down to the following, or at least it won't help matters.
for(i = 1;i < 3;i++){
....
}
Will only access the first two atoms of your array and will exit the loop before iterating the third time. Try
for(i = 1;i < 4;i++){
....
}
Similarly it is good practice to start array indices at 0 in which case
for(i = 0;i<3;i++){
....
}
would iterate through each (assuming the start index is 0)
Related
I have a form that has multiple fields all with the same class. These are populated with URL's that follow the same structure. I am trying to extract the same section from each URL. So far var res = x.split('/')[5]; will achieve this but only for the first URL. I can also use var x = document.querySelectorAll(".example") to change all the url's but I cannot find the correct way to combine both of these function. so far my code looks like this:
script>
function myFunction() {
var x = document.querySelectorAll(".example").innerHTML;
var res = x.split('/')[5];
var i;
for (i = 0; i < x.length; i++) {
x[i].innerHTML = res;
}
}
</script>
I have looked around but can't find a solution that fits. Thanks in advance for your help.
So loop over the HTML Collection, this is making assumptions based on code.
// Find all the elements
var elems = document.querySelectorAll(".example")
// loop over the collection
elems.forEach(function (elem) {
// reference the text of the element and split it
var txt = elem.innerHTML.split("/")[5]
// replace the text
elem.innerHTML = txt
})
<div class="example">1/2/3/4/5/a</div>
<div class="example">1/2/3/4/5/b</div>
<div class="example">1/2/3/4/5/c</div>
<div class="example">1/2/3/4/5/d</div>
<div class="example">1/2/3/4/5/e</div>
<div class="example">1/2/3/4/5/f</div>
I have several div tags trainingData0, trainingData1, trainingData2, etc that I am trying to use innerHTML to update text.
I am trying to refer to them with a for loop but it doesn't work. (even though trainingDataDiv does hold the correct value ie trainingData0 which DOES work if I type trainingData0.innerHTML )
Any advice? Thanks in advance.
<div id="trainingData0"></div>
---------------
for (var i=0; i<15; i++)
{
var trainingDataDiv = "trainingData" + i;
trainingDataDiv.innerHTML = data;
}
Answer by Robby Cornelissen in comments of my question :)
for (var i=0; i<15; i++)
{
var trainingDataDiv = document.getElementById("trainingData" + i);
trainingDataDiv.innerHTML = data;
}
So you don't have to change your max number when you change the number of elements:
//Get all elelemtns with ids that start with trainingData
var trainingDataDivs = document.querySelectorAll("[id^='trainingData']");
var data = "I'm training Data";
//iterate the elements we found earlier and update the data
for(var i = 0; i < trainingDataDivs.length; i++)
{
trainingDataDivs[i].innerHTML = data;
}
<div id="trainingData0"></div>
<div id="trainingData1"></div>
<div id="trainingData2"></div>
<div id="trainingData3"></div>
<div id="trainingData4"></div>
<div id="trainingData8"></div><!-- Note the gap in numbers -->
<div id="bob">I'm not training</div>
For more info see Attribute selectors and querySelectorAll
given the following:
<div ID="parent">
<div ID="child1">Children Stuff</div>
<div ID="child2">More Childish things</div>
</div>
<div ID="orphan">Whhhaa I want a mommy</div>
var p = document.getElementById("parent");
var c = document.getElementById("orphan");
p.appendChild(c);
var ch = p.childNodes;
var ln = p.children;
for(var i=0;i < ln.length; i++) {
console.log(ch[i]);
}
console.log(ln.length);
The console output provides:
<div ID="child1">Children Stuff</div>
<div ID="child2">More Childish things</div>
3
Here's where I am lost:
I need to obtain information out of each child node (including the new child). Naturally I won't be simply outputting it to a console, I need to perform some logic on other DOM elements that share similar IDs as the children.
Why doesn't the element.childNodes; call pick up on the new child?
Any help is appreciated.
The above is sample air-code so I apologize if the syntax is not 100%, but I'm hoping the point gets accross nonetheless.
You're looping over ln.length but reading ch:
for(var i=0;i < ln.length; i++) {
console.log(ch[i]);
}
That gets confusing very quickly, as ln has a length of 3 and contains the child elements. ch has a length of 6 and contains all elements (including 3 text elements with just line feeds).
This is really easy to see if you just add 2 more console logs:
console.log('ch',ch);
console.log('ln',ln);
As here: https://jsfiddle.net/mqhevnsu/
Because you mix childNodes and children. Try using only children:
var p = document.getElementById("parent");
var c = document.getElementById("orphan");
p.appendChild(c);
var ln = p.children;
for(var i=0;i < ln.length; i++) {
console.log(ln[i]);
}
console.log(ln.length);
<div ID="parent">
<div ID="child1">Children Stuff</div>
<div ID="child2">More Childish things</div>
</div>
<div ID="orphan">Whhhaa I want a mommy</div>
It just works if you fix the typos and become consistent in using p.children or p.childNodes:
var p = document.getElementById("parent");
var c = document.getElementById("orphan");
p.appendChild(c);
var ch = p.children;
for(var i=0;i < ch.length; i++) {
console.log(ch[i]);
}
console.log(ch.length);
jsfiddle
I want to convert this code into an array.
<div id="Parent">
<div class="childOne" ><span id="1dfgdffsf">ChildOne </span></div>
<div class="childOne" ><span id = "2sdfsf">ChildTwo</span> </div>
<div class="childOne" ><span id="3sdfsf">ChildThree </span></div>
<div class="childOne" ><span id="4dssfsf">ChildFour </span></div>
</div>
span id is dynamic. therefore i can't use it.please tell me how to convert it into an array.
You will have to loop over each element and push it into an array
//declare an array
var my_array = new Array();
//get all instances of the SPAN tag and iterate through each one
$('div#parent div.childOne span').each(function(){
//build an associative array that assigns the span's id as the array id
//assign the inner value of the span to the array piece
//the single quotes and plus symbols are important in my_array[''++'']
my_array[''+$(this).attr('id')+''] = $(this).text();
//this code assigns the values to a non-associative array
//use either this code or the code above depending on your needs
my_array.push($(this).text());
});
If you do not use a library, the following should work fine:
var result = [], matches = document.querySelectorAll("#Parent span");
for (var i = 0, l = matches.length; i < l; i++)
result.push(matches[i].getAttribute("id"));
Else if the document.querySelectorAll function is not supported:
var result = [], parent = document.getElementByID("Parent");
for (var i = 0, l = parent.childNodes.length; i < l; i++)
result.push(parent.childNodes[i].childNodes[0].getAttribute("id"));
If you wanted to get key/value pairs instead you can do the following:
var result = [], matches = document.querySelectorAll("#Parent span");
for (var i = 0, l = matches.length; i < l; i++)
result[matches[i].getAttribute("id")] = matches[i].text;
With jQuery it is as simple as a single line of code:
var result = $("#Parent span").map(function() { return $(this).attr("id"); }).get();
First of all, try to avoid naming id's and classes from capital letters.
Then try this:
var arr = [];
$('#parent').children().each(function(){
arr.push($(this).find('span').text());
}
maybe this is the best way currently
const array = Array.from(document.querySelectorAll('.childOne'));
Below Code May be help you :
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>First</div>
<div>Second</div>
<div>Third</div>
<div>Fourth</div>
<script>
var elems = document.getElementsByTagName("div"); // returns a nodeList
var arr = jQuery.makeArray(elems);
arr.reverse(); // use an Array method on list of dom elements
$(arr).appendTo(document.body);
</script>
</body>
</html>
This would be simple one, as :
jQuery(function($) {
var anArray = [];
$("#Parent").find("span").each(function(){
anArray.push($(this).html());
});
alert(anArray);
});
<body>
<section id="que-container">
<div class="num" style="display: none">1000</div>
<section id="numberContainer">
<span class="number"></span>
</section>
<br class="clear">
</section>
<script src="components/jquery/jquery.min.js"></script>
<script src="components/bootstrap/js/bootstrap-button.js"></script>
<script src="components/bootstrap/js/bootstrap-carousel.js"></script>
<script src="js/scripts.js"></script>
<script>
$(document).ready(function(){
var numbers = $('.number');
var num = $(".num").html();
var arr = num.split('');
for (var i = 1; i < arr.length ; i++) {
$('#numberContainer').append(numbers.clone());
$('.number').append(arr[i]);
}
$('.number').each(function(i, val) {
$(this).addClass('numStyle');
})
});
</script>
</body>
I am trying to get the values inside the '.num' div, convert it to an array and append the array's items to the '#numberContainer' within spans with the 'number' class. i am not getting any errors on the console but the code doesnt seem to work. any help? thanks
Your code has to be like this because arrays are 0 index based:
fiddle: http://jsfiddle.net/DZJ6p/
var numbers = $('.number');
var num = $(".num").html();
var arr = num.split('');
for (var i = 0; i < arr.length; i++) {
$('#numberContainer').append(numbers.clone().append(arr[i]));
}
$('.number').each(function(i, val) {
$(this).addClass('numStyle');
});
you have a wrong selector here
$('.numbers').append(arr[i]); // i didn't find any element with numbers class
it should be
$('.number').append(arr[i]);
OR
numbers.append(arr[i]);
UPDATED
your for loop starts with var i as 1... so it is missing the first index of arr i.e. arr[0], I used this in youe code..
$('#numberContainer').append(numbers.clone().append(arr[i])); // u can use text(arr[i])) here
here is the fiddle...
http://jsfiddle.net/zLHxV/
i am not sure why you are using $('#numberContainer').append(numbers.clone());. Can you take a look at the js fiddle where i have put your code there.