Passing array elements to foreach divs - javascript

I'm trying to pass string elements from an array myArr while selecting the div it should go into with a forEach loop, so that each of the four div elements below has a corresponding string element from the array.
I'm having some trouble with it, because I'm selecting the divs with a querySelectorAll method. Help would be appreciated. This code below is just a sample of what I'm working on, so it can't be altered too much.
HTML
<div class="number">old number</div>
<div class="number">old number</div>
<div class="number">old number</div>
<div class="number">old number</div>
JS
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
numberDivs.forEach(function(el) {
el.innerHTML = "new number";
for (var i = 0; i < myArr.length; ++i) {
el.innerHTML = myArr[i];
}
});
Right now, it's (el) only passing through the last element in the array to all divs, instead of the corresponding one.

I think is this what you want:
numberDivs.forEach(function(el, i) {
el.innerHTML = myArr[i];
});
This assumes they are of equal length, and won't overwrite each element's HTML like your code is currently doing.

var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
for (var i = 0; i < myArr.length; i++) {
numberDivs[i].innerHTML = myArr[i];
}
You're issue was you had a for loop going across all the elements, then another for loop going across your array. The inner for loop, the one for you're array, would always end at the last element, therefore each object - the divs - ended at the final element of that array.
http://jsfiddle.net/a8zrkejo/

Quick fix, if you're certain the total count of the array is same as the number of divs
then loop the array only and use the index of each element to access the div.
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
myArr.forEach(function(value, Index) {
numberDivs[Index].innerHTML = value
});

Related

Add data in Object Array

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>

How do I prevent two identical elements to be printed in a table?

I'm writing a javascript code, where the user should be able to search through dimension elements, which is displayed within a "pop-up" window with a table.
The code that displays the elements in the array looks like this:
$element.find("#myInput").on("qv-activate", function (){
let elemList = [];
self.backendApi.getData(requestList).then(function (dataPages) {
let elem = dataPages[0].qMatrix;
for(let i = 0; i < elem.length; i++){
elemList.push(elem[i][0].qText);
}
$(document).ready(function () {
$("#myInput").on("keyup", function () {
var value = $(this).val().toLowerCase();
for (var i=0; i<elemList.length; i++) {
if (elemList[i].toLowerCase().indexOf(value) >= 0){
$element.find('#searchTable').prepend('<tr><td id="searchElem">' + elemList[i] + '</td></tr>');
}
}
});
});
})
})
The only problem is, when I use the searchbar, it presents the element multiple times. Is there a way I can make sure, that the .prepend() only prepends if it is not the same value as before?
Some kind of; if element value is identical with the before prepended value, then don't prepend?
Hope it makes sense, and you have a solution to my problem.
Thanks!
Instead of calling prepend in the second for loop, make a new array and append elemList[i] to that.
Then use a solution from "Get all unique values in an array (remove duplicates)" to remove the duplicates from the array. For example, if values is your new array:
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
values = values.filter(onlyUnique);
Finally, loop through your new array and call prepend on each.

For loop within a for loop? - Javascript

newbie javascript question. I made sure to research as much as I could before posting here, I've tried many solutions but could be searching for the wrong thing.
I've attached an image below of the issue I have. I'm trying to retrieve everything in the dark blue boxes, but I can't identify those input tags as there is nothing unique about them, I can however identify their parent divs by the class 'f-active'. When the divs have that class they have been selected by the user which is what I am interested in.
My attempt so far
var divArray = document.querySelectorAll('div.add-filter.f-active');
var arr = [];
for(var i=0; i < divArray.length; i++){
var childArray = divArray[i].children;
// console.log(childArray);
for(var i=0; i < childArray.length; i++){
if(childArray[i].tagName == "INPUT"){
var catNameCollection = arr.push(childArray[i].name);
// console.log(catNameCollection);
}
}
}
I tried to use a for loop to get all the parents, then use another for loop to select the children (input tags) and then grab the name attribute, however it is just outputing numbers. I did originally try to create 'divArray' as document.querySelectorAll('div.add-filter.f-active').children, but this and then grab the name attribute in the for loop, but this didn't return anything at all.
Any help anyone could offer would be greatly appreciated, I'd love to know what I'm doing wrong.
Thank you!
Your i is same for both loops. Use:
var divArray = document.querySelectorAll('div.add-filter.f-active');
var arr = [];
for(var i=0; i < divArray.length; i++){
var childArray = divArray[i].children;
// console.log(childArray);
for(var k=0; k < childArray.length; k++){
if(childArray[k].tagName == "INPUT"){
var catNameCollection = arr.push(childArray[k].name);
// console.log(catNameCollection);
}
}
}
Classic for-loops usually aren't the best tool for iterating through DOM elements - they add a lot of clutter and are error-prone, especially when you have to nest them.
In your case it'd be simpler to instead modify your query to directly grab all input elements with a div.f-active parent, then extract the names by iterating through them with a forEach. For example (using ES6 or higher):
const arr = [];
// Get list of all <input> elements that have <div> element parents with class f-active.
const nodes = document.querySelectorAll('div.add-filter.f-active > input');
// Extract name from each input element matched by your selector.
nodes.forEach(node => arr.push(node.name));
Or if you're stuck using ES5:
var arr = [];
var nodes = document.querySelectorAll('div.add-filter.f-active > input');
nodes.forEach(function(node) {
arr.push(node.name);
});
Here's a quick JSFiddle I put together to demonstrate the concept for you. (You'll need to open the console to see the result)
Hopefully that helps :)

Get length of longest String in Array

i need to find out the longest string of an array. First of all i push different "text" elements into my array, since the stringe and amount of those "text" elements can differ from case to case. (they are lables of an chart and thus are generated based on the charts sections.
my code right now looks like this:
var textLengthArray = [];
domContainer.find(" g > .brm-y-direction > .tick > text").each(function () {
textLengthArray.push($(this));
});
var lgth = 0;
var longestString;
for (var i = 0; i < textLengthArray.length; i++) {
if (textLengthArray[i].length > lgth) {
var lgth = textLengthArray[i].length;
longestString = textLengthArray[i];
}
}
It already pushes all text elements into my array. But when i use
alert(longestString.length)
i allway get "1" as a result. I am pretty shure i have to add .text anywhere before .length, since the code does not check die textlength of the textelements.
Since i am quite new to javascript i would highly appreciate some help.
Thanks in advance!
textLengthArray.push($(this)); should be textLengthArray.push($(this).text()); otherwise your array consists of jQuery objects. And indeed jQuerySet has length property. And in your case the set consists of 1 element.
You are re-declaring lgth in each iteration of the array which is re-assigning the value.
Replace var lgth = textLengthArray[i].length with lgth = textLengthArray[i].length and you should be good.
I don't know about the rest of your code, looks fine. But you're pushing a jQuery object$(this), not a string. Line three should read textLengthArray.push(this);.
Apparently one of the strings your pushing is a valid jQuery selector that finds an element :-)
No need to create a separate array. Just iterate objects and update as you go:
longest = "";
$('div').each(function() {
var t = $(this).text();
if(t.length > longest.length)
longest = t;
});
alert(longest)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>hello</div>
<div>wonderful</div>
<div>world</div>
To get the longest string from any array, try reduce:
a = ['hello', 'wonderful', 'world']
longest = a.reduce(function(prev, e) {
return prev.length >= e.length ? prev : e;
});
alert(longest)
Sort the array by length and get the first element. Hope it works for you
stackoverflow.com/questions/10630766/sort-an-array-based-on-the-length-of-each-element

How to add div id name to array

At the page I have these divs:
<div id="question-688">
</div>
<div id="test">
</div>
<div id="stats-654">
</div>
<div id="answer-636">
</div>
<div id="someDiv">
</div>
I would like to create an array with these numbers: 688, 654, 636. So when id of div is started with question or answer or stats, I want to add number belongs to this ID to array. How can I do this via javascript?
You can use a plain css selector with method document.querySelectorAll.
I used Array.prototype.map.call because the previous method returns a NodeList not an Array, then you can use map and pass it a function to extract the ids of your divs.
Demo here
var selector = 'div[id^=stats-],div[id^=answer-],div[id^=question]',
ids = Array.prototype.map.call(document.querySelectorAll(selector), function (div) {
return div.id.split('-')[1]|0; // this returns the id as an integer
});
Here is a working jsBin : http://jsbin.com/pecaj/1/edit
var arrayOfNumbers = [];
var divArray = document.querySelectorAll("div");
for(var index = 0; index<divArray.length; index++) {
var id = divArray[index].id;
if(id.match(/\d+$/)) {
arrayOfNumbers.push(parseInt(id.match(/\d+$/),10))
}
}
console.log(arrayOfNumbers)
It fetches the number for div ids and adds them to an array.
Hope its useful to you :)
Only ONE instruction if you use jquery :
var yourArray=$('div[id^=stats],div[id^=question],div[id^=answer]').toArray().map(function(e){return $(e).attr('id').split('-')[1]}) ;
See fiddle : http://jsfiddle.net/abdennour/LBc5u/
Very simple:
var divs = document.getElementsByTagName('div');
var divIDs = [];
var r = /\d+/;
for (var i =0; i < divs.length; i++) {
if (divs[i].id.length > 0 && ( divs[i].id.indexOf("question") !=-1 || divs[i].id.indexOf("answer") !=-1 || divs[i].id.indexOf("stats") !=-1 ))
divIDs.push((divs[i].id).match(r));
}
Demo http://jsfiddle.net/P3LPn/
maybe something like this? Create a map and them use the map to refer to your DIV's
var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;

Categories