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;
Related
I have been trying to change a for loop to filter() one-liner, but I get this error: (index):44 Uncaught TypeError: childrenElements.filter is not a function .
Working code snippet:
const parentElement = document.querySelector('.container');
let childrenElements = parentElement.children;
let results = [];
for(i = 0; i < childrenElements.length; i++){
if( childrenElements[i].classList.contains('ui-widget')){
results.push('ui-widget')
}
}
Not Working code snippet:
const parentElement = document.querySelector('.container');
let childrenElements = parentElement.children;
let results = [];
results = childrenElements.filter(childrenElement => childrenElement.classList.contains('ui-widget') )
I think it's because it doesn't recognize the childrenElements as array, but I'm not sure how to fix it.
You can find a demo here.
EDIT:
The accepted's answer final code snippet is the following:
const parentElement = document.querySelector('.container');
let childrenElements = parentElement.children;
let results = [];
results = [...childrenElements].map(childrenElement => childrenElement.classList );
console.log(results)
if (results[0].contains('ui-widget')) {
alert('it has class')
}
You can convert your HTMLCollection object to an array using the spread operator, so that your data is iterable:
results = [...childrenElements].filter(childrenElement => childrenElement.classList );
However, it seems like you are trying to look for a particular class in the elements. For that you should map over your elements to create an array of classList arrays and then use contains to search for the element you're looking for.
results = [...childrenElements].map(childrenElement => childrenElement.classList );
if (results[0].contains('ui-widget')) {
alert('it has class');
}
The reason for that is that childrenElements is a HTMLCollection that is enumerable, which means you can access its objects using indexes. E.g. childrenElements[0]
However, it does not provide the same methods provided by the Array object. Therefore, you will need to convert it to an Array by using:
Array.from(childrenElements)
Then, you can use all of the methods provided for an Array.
Please be aware that if your list is too big, this might not be the most performant way as you are converting your HTMLCollection to an Array and then, looping all over again on it to filter elements.
In your code childrenElements is HTMLCollection which is array like object not an array. So, you just need to convert that to array and it will work.
const parentElement = document.querySelector('.container');
let childrenElements = parentElement.children;
console.log(childrenElements)
let results = [];
// working code snippet - uncomment to test it
/* for(i = 0; i < childrenElements.length; i++){
if( childrenElements[i].classList.contains('ui-widget')){
results.push('ui-widget')
}
}
console.log(results) */
// not working code snippet
results = Array.from(childrenElements).filter(childrenElement => childrenElement.classList )
console.log(results)
if (results[0] === 'ui-widget') {
alert('it has class')
}
<div class="container">
<div class="ui-widget ui-widget-content widget-left">
I am a ui-widget
</div>
<p class="paragraph">
Hello Paragraph
</p>
<button class="btn">
Close
</button>
</div>
Use this function to turn it into an array
var realArray = Array.from(childrenElements);
I want to delete the element from json array using nodejs. My json file match.json is as follows.
[{"id":"1234","time":"3"}]
from this I want to delete the first element so that the json file looks like this:
[]
I tried the following code,its printing an empty array in the console but it is not removing the elements from the match.json file
for(var i=0;i<w;i++)
{
for(var j=0;j<m;j++){
if((words[i].id==match[j].id) && (words[i].time==match[j].time))
{
var f1=0;
//var id1=match[j].id;
var linkadd=words[i].link;
delete match[j];
console.log(match);
}
}
}
Use match.splice(i, 1) instead of delete match[i]
var arr = JSON.parse(Match_json_data);
// remove 1st element
var indexOfItemToRemove = 0;
var noOfItemsToRemove = 1;
arr.splice(indexOfItemToRemove, noOfItemsToRemove);
Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice?v=control
This should work:
let myJsonString = '[{"id":"1234","time":"3"}]';
let myEditedJsonString = JSON.stringify(JSON.parse(myJsonString).shift());
to remove the element..you can use splice.. The element will be removed.
{
var f1=0;
//var id1=match[j].id;
var linkadd=words[i].link;
match.splice(i, 1);
console.log(match);
}
If you use delete match[i], the list becomes [undefined]. So use splice.
So basically delete does not delete the element, rather it sets the element as undefined.
const items = [{"id":"1234","time":"3"}]
console.log('before removing item ==> ', items)
items.splice(0 /*index to be removed*/, 1/*no. of items to be removed*/)
console.log('after removing item ==> ', items)
If you want to always take out the first element and update the array the use the following code.
var arr =[{"id":"1234","time":"3"}]
arr.reverse().pop()
If you want to get a subset of the array you can slice the array but it will not update the array but create a new array.
arr.slice(STARTING_ADDRESS,NO_OF_ELEMENTS_TO_SLICE)
NOTE: This will return a new array, So if you want to update the old array then you need to assign it to the old array.
arr = arr.slice(STARTING_ADDRESS,NO_OF_ELEMENTS_TO_SLICE)
I'm trying to get the last item in a array using JavaScript.
But I'm always getting all items in the array.
So far, I've tried several methods. Here is my code:
var pathCoords = ['1','2','3','4','5'];
var sample1 = pathCoords[pathCoords.length -1];
var sample2 = pathCoords.slice(-1)[0];
console.log(sample1, sample2);
Maybe You can use splice method of array like this :
var sample = pathCoords.splice(pathCoords.length-1);
Hi I have use the following code snippet to create the array .
var rows = [];
rows["_id1"] = 1;
but in this case 1 did not insert into the array. Is there any other way to achieve this.
Screenshot:
Make it an object.
var rows = {};
rows["_id1"] = 1;
Or if you really want an array, you can have an array of objects
rows.push({"_id1": 1});
I currently the following jQuery collection / object:
[li.row-0, li.row-1, li.row-2, li-row-2, li.row-2, li.row-3]
Each class name is dynamically added to each element by a previous method. The only consistent part of the class name is row-. The number can be anywhere from 0 - ∞.
I want to create a new array or object of elements that are grouped by same dynamic class name:
[li.row-0]
[li.row-1]
[li.row-2, li.row-2, li.row-2, li.row-2]
[li.row-3]
The above is just a guess of the outcome, as I am not 100% sure how best to achieve this.
The aim is to be able to loop through .row-0, .row-1, .row-2, .row-3 and do something with the elements in each individual row.
I would do this :
var map = [].reduce.call(arr, function(map, v){
(map[v.className]||(map[v.className]=[])).push(v);
return map;
}, {});
var arr2 = [];
for (var className in map) arr2.push(map[className]);
The reduce builds a map having as keys the class names and with values the arrays of the elements having that class name.
I use [].reduce.call(arr, instead of arr.reduce( so that it works for standard arrays, jQuery collections, nodelists, etc.
Then the loop builds an array from that map. You might find the map more useful than the final array.
This shows you a general way of achieving this, though you're probably using elements rather than strings, but hopefully this will help
var tst = ['li.row-0','li.row-1','li.row-2','li.row-2','li.row-2','li.row-3'];
var grouped = [];
for(var i in tst)
{
var text = tst[i];
var num = text.replace('li.row-','');
if(!grouped[num]) grouped[num] = [];
grouped[num].push(text);
}
console.log(grouped);//[["li.row-0"], ["li.row-1"], ["li.row-2", "li.row-2", "li.row-2"], ["li.row-3"]]
Using elements:
var tst = [li.row-0,li.row-1,li.row-2,li.row-2,li.row-2,li.row-3];
var grouped = [];
for(var i in tst)
{
var text = tst[i].className;
var num = text.replace('row-','');
if(!grouped[num]) grouped[num] = [];
grouped[num].push(text);
}
console.log(grouped);//[["li.row-0"], ["li.row-1"], ["li.row-2", "li.row-2", "li.row-2"], ["li.row-3"]]
This method is more verbose and allows more complex grouping if need be (if other attributes come into play)
I would do something like the following:
var arr = ['li.row-0', 'li.row-1', 'li.row-2', 'li.row-2', 'li.row-2', 'li.row-3'];
var result = {};
$.each(arr, function (index, item) {
var ind = item.toString().split('row-')[1];
(result[ind] || (result[ind] = [])).push(item);
});
console.log(result);