Getting into all entries by querySelectorAll in JS - javascript

Yesterday, I've asked the same, by today I'm little more specific. I want to get those div values into the generated link, so link would be like: https://stackoverflow.com/value1 value2 value3
<div class="example">value 1</div>
<div class="example">value 2</div>
<div class="example">value 3</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.querySelectorAll('.example');
var i;
for (i = 0; i < x.length; i++) {
x[i].innerText;
}
window.open('https://stackoverflow.com/'+x ,'_blank', "width=550, height=550");
}
</script>
All i'm getting is https://stackoverflow.com/[object NodeList]
Can you help me how to handle this?

All i'm getting is https://stackoverflow.com/[object NodeList] Can you
help me how to handle this?
Because x is still the nodeList and you are not assigning anything to x, you need another accumulator
var value = [];
for (i = 0; i < x.length; i++) {
value.push( x[i].innerText);
}
value = value.join(" "); //not sure why you need space delimited values
window.open('https://stackoverflow.com/'+value ,'_blank', "width=550, height=550");

Just having the line x[i].innerText; on its own returns the value of innerText but crucially you're not storing the result anywhere.
In the window.open() function the value of x is an object not a string.

Related

JS exstract part of URL from multiple form fields

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>

innerHTML and use of Array

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

Javascript - element.childNodes does not see an append.newchild

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

Trying to convert the values in a node to an array, clone a specific element and append the array items to that node with a class

<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.

Adding multi addEventListener to specific function

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)

Categories