Have a litle problem here with multiple array in Javascript.
I define the array like this: var list = [];
In html I have <img class="Img" id="2" src="/test.png"/>
My goal is to make a multiple array like this on "onload":
list[2][test.png]
Where 2 is the id tag, and the other is the image. In that way I later can do a loop and collect all photos belonging to list[2] or list[3] is that ID exist.
But my problem is, I can't get this to work. I tried this:
var images = document.getElementsByClassName("Img");
for(var i=images.length; i--;) {
var PhotoId = images[i].getAttribute('id'), // Id on the photo
image = images[i].getAttribute('src'); // The images
}
If I now in the loop this.list.push(image) it work like a charm, but that is one-dimensional.
How can I use this PhotoId as I explained above?
in single line u can also do it as, check if list[photoId] array already exists, if yes then push the image into it otherwise create an empty array.
list[photoId] ? list[photoId].push(image) : (list[photoId] = []).push(image);
Try this,
var images = document.getElementsByClassName("Img");
var arr=[];// array
for(var i=images.length; i--;) {
var PhotoId = images[i].getAttribute('id'), // Id on the photo
image = images[i].getAttribute('src'); // The images
arr[PhotoId]=image;
}
console.log(arr);
You can use
this.list[photoId] = []
then
this.list[photoId].push(image)
On another note id should be unique in DOM. If you want to group elements with certain property then use class attribute.
Related
I have some tables that have data and can using it on <td>. So more like it I have something like this (show on images below)
My Element
I want to get that all positions Name and put it into an array so I can make of use that array I tried to use this code and got undefined
script.js
/** Checking if There positions name */
function checkPositions(){
let positions = document.getElementsByClassName('check-positions').innerHTML;
let array = [];
array.push(positions);
console.log(array);
}
Then how can I get that value??
The problem that you have is that document.getElementsByClassName('check-positions') returns a HTMLCollection which does not have an innerHTML property.
What you need to do is convert the HTMLCollection into an array, and then read the innerHTML property for each of the items in the array. See the following example:
const elements = document.getElementsByClassName('check-positions');
const positions = Array.from(elements).map(element => element.innerHTML);
console.log(positions);
<div class="check-positions">1</div>
<div class="check-positions">2</div>
<div class="check-positions">3</div>
Use like this
let positions = document.getElementsByClassName('check-positions')[0].innerHTML;
It's showing none because u r fatching whole array and pushing it without using indexes
Code
function checkPositions(){
all_ele = document.getElementsByClassName('check-positions')
length = all_ele.length
let array = [];
for( let i=0;i<length;i++)
{
let positions = document.getElementsByClassName('check-positions')[i].innerHTML;
array.push(positions);
}
console.log(array);
you can use jquery code to do this.
var arr = [];
$("#tablePlacement tr").each(function() {
var name = $(this).children('td.check-positions').text();
arr.push(name);
});
You should use
let positions = document.getElementsByClassName('check-positions').innerText;
So, I have an input, I enter words for filter answers.
My answers are my panel.
I create an Array for register my answers.
var array = [];
But when I finish my loop, I want to innerHTML my datas who are in my Array.
But I have a [object HTMLDivElement] because i push Object in Array.
Ok my question is = How can I create an Array Object and push my panel in
var obj = {}
And How can I display them
This code search in answer if the words exist
if (searchIndex > -1) {
If the answer exist , push the panel in my array and count how many answer he founds
array.push(panel);
countFound++;
}
When the loop is finish, exploit this data and display them
array1.forEach(function(element) {
// I dont know how is the method to exploit all data one by one
});
Depending on what your HTML looks like, you should use innerHTML attribute to get the contents of an element.
array.push(panel.innerHTML);
You get the object HTMLDivElement because that's what panel is.
If you want to iterate over the elements in array you can do it with a foor loop, alternative with a foreach loop, and to display it again in the HTML you once again need to use the innerHTML attribute.
text = "";
for (i=0; i < array.length; i++) {
text += array[I];
}
document.getElementById("result").innerHTML = text;
And of you want to repeat the procedure you need to empty the array variable afterwards:
array = []; // Add this line after appending your data to the HTML.
// Realistically after the for loop
For more Details go to adding-elements-to-object
Here is how it works:
var element = {}, cart = [];
element.id = 1;
element.panel = document.getElementById("panel");
cart.push(element);
alert(cart[0].panel);
<div id="panel"></div>
I need to work with variables dynamically, and get them dynamically too. The first thing I need to know is:
How to save a variable reference(NOT its value) in a collection?
Example:
var divA = "<div>my div A</div>";
var divB = "<div>my div B</div>";
var divC = "<div>my div C</div>";
Then, save in a collection:
var mySet = new Set();
function returnDivA(){
return divA;
}
function returnDivB(){
return divB;
}
function returnDivC(){
return divC;
}
mySet.add(returnDivA());//I would like save the varible ref in a collection.
mySet.add(returnDivB());
mySet.add(returnDivC());
I want the Set collection to save the variables(NOT its values), it means:
var mySet = new Set(divA, divB, divC);
Then, with that, my intent is to do something like that:
var totalOfDivs;
for(var i = 0; i < mySet.size; i++){
totalOfDivs += mySet[i];
}
$("#anotherDIV_to_show_all_divs").html(totalOfDivs);//Then, here, I want to show all divs in the screen.
I would like suggestions, please!
It solved my problem to put variable dynamically in html using this in a for loop:
$("#anotherDIV_to_show_all_divs").append(mySet[i]);
About saving javascript variable reference in a Collection, I understand that I can't do that, because of the answer of the adeneo in comment:
"There is no "reference", all variables are pass-by-value in javascript..."
Read the documentation about set.
enter link description here
I guess you have to loop your set like this.
var totalOfDivs= "";
for (let item of mySet.values()) {
totalOfDivs+= item;
//console.log(item);
}
$("#anotherDIV_to_show_all_divs").html(totalOfDivs);
I am looking to create an array of all the images in a string of HTML.
I've tried using the following but it generates errors if the complete URL path is not present in the src.
var found = $(html).find('img');
$("img").each(
function(index) {
theArray.push( $(this).attr("src") );
});
Quick run down of how to achieve this:
Open with jQuery's DOM Ready function ->
$(function(){
Create the variable found which holds a collection of the elements.
var found = $('p > img');
Create an empty Array to hold our results.
var results = new Array();
Iterate through each of the elements that we found
$.each(found, function(index,value){
For each 'value' (the item) that we find, we want to take the src, and push that src into the array.
results.push($(value).attr('src'));
Erroneous closure
});
Alert the total amount of items in the array;
alert('There is a total of '+results.length+' results in the Array.');
Alert just the src of the 3rd item we added to the array.
alert('The src of the 3rd item is: '+results[2]); //3nd item in array, indexes are 0 based
Erroneous closure
});
Hopefully this helps clear things up a bit.
You can do that with simple and plain JavaScript by creating an "instant" html element:
Create a element
Insert the string as innerHTML
Query the node
Example:
var html = "<html><body><img src='/img1.png' /><br /><img src='/img2.png' /></body></html>";
var node = document.createElement("div");
node.innerHTML = html;
for(var i=0; i < node.children.length; i += 1) {
if (node.children[i].tagName === 'IMG') {
alert(node.children[i].src)
};
}
Just try this:
var imgArray = $('img'),
srcArray = [];
console.log(imgArray); // array of imgs
$.each(imgArray, function() {
srcArray.push(this.src));
});
What is the cleanest way to put the source attribute string of all images within a div into an array?
I was hoping this would work -
var imageSourceArray = $("#leDiv img").attr('src');
alert(imageSourceArray[3]); //not alerting the source, boo hoo.
Do I need to loop through $("#leDiv img") and add each src string to an array individually? Or is there a more elegant way to do this?
You can use jQuery's map function which is described as:
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
For your example:
var mySources = $('#leDiv img').map(function() {
return $(this).attr('src');
}).get();
Edit: Far more elegant solution, there's obviously still some looping involved internally:
var img_sources = $('#leDiv img').map(function(){ return $(this).attr('src') });
You will in fact need to loop over the collection and add sources individually.
var img_sources = [];
$('#leDiv img').each(function(i,e){
img_sources.push($(e).attr('src'))
})
Some background: jQuery.fn.attr() maps to jQuery.access() internally, the key part of which looks like this:
function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// setter functions omitted here …
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
}
Note the elems[0] part – only the first item in the collection is fed to the subsequent callback function (jQuery.attr() in fact) responsible for extracting the information.
var imageSourceArray = [];
$('#leDiv img').each(function(){
var src = $(this).attr("src");
imageSourceArray.push(src);
});
alert(imageSourceArray[3]);
you already have the src in a collection when you fetch the the images. It may be more efficient to not store the src attributes in another array:
$('#leDiv img').each(function(i,e){
var dosomethingwith = $(e).attr('src');
})
or you could do:
var ImageCol = $('#leDiv img');
alert(ImageCol[3].attr('src'));