how to convert div data into array using javascript or jquery? - javascript

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);
});

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>

Printing an Ordered List from a JS file

I have a js file with the following array
var fruits = [ "Apples","Oranges","Pears","Grapes","Pineapples","Mangos" ];
In my HTML file I want to create a container and write an ordered list containing all the fruits in the array to the container I just created, however I'm having serious trouble and I can't find much online help. I'm a beginner, this is what I have
<div class = "container1">
</div>
<h3>Fruits</h3>
<html>
<head>
<script src="Web Programming/Assignments/Assignment #3/assignment3/list.js"></script>
</head>
<body>
<div container1= "fruits"></div>
</body>
You should give the element an id, your custom html attribute would work as a selector, but the typical way would be the id. Then you can simple create some elements in a loop, giving them the element's text content:
var fruits = [ "Apples","Oranges","Pears","Grapes","Pineapples","Mangos" ];
var el = document.getElementById('fruits');
var ol = document.createElement('ol');
el.appendChild(ol);
fruits.forEach(function (fruit) {
var f = document.createElement('li');
f.appendChild(document.createTextNode(fruit));
ol.appendChild(f);
});
<div id="fruits"></div>
Just in case you insist on the container1=... you can select that with
var el = document.querySelector('div[container1="fruits"]');
Firstly include your script in your html file. At the bottom of the body.
Give your container id of container or as you like.
And code will be something like this:
var arrayFruits = ["bananas", "apples", "etc"];
var container = document.getElementById("container");
for (var i = 0; i < arrayFruits.length; i++) {
var list = document.createElement("li");
list.innerHTML = arrayFruits[i];
container.appendChild(list);
}

How to write all data from Array?

I have HTML like :
<div id="divid">
1
2
3
.....................
</div>
I have script to get all links from a div like :
<script>
var links = document.getElementById('divid').getElementsByTagName('a') ;
</script>
Then I want write link into class like :
<script>
var links = document.getElementById('divid').getElementsByTagName('a') ;
document.write("<div class="'+link[1]+" "+ link[i]+'">Class is added links</div>");
</script>
That mean after write I have HTML:
<div class="d#link1 d#link2 d#link3">Classes is added links</div>
How can I do this? Using for loop or not? how?
You have to get the href property from each element. Put them in an array, and you can just join the strings:
var elements = document.getElementById('divid').getElementsByTagName('a');
var links = [];
for (var i = 0; i < elements.length; i++) {
links.push(elements[i].href);
}
document.write("<div class="' + links.join(" ") + '">Class is added links</div>");
Use join in combination with map:
var classString = links.map(function(link) { return link.attributes.href; } ).join(' ');

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