get ALL id's of children elements - javascript

How do I get an array or something similar with ALL the id's of elements to a certain div?
Let's say I have someting like this:
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
I would then like an array that look's something like this
parent-div [
0: "div-no-1",
1: "div-no-2",
2: "div-no-3",
3: "div-no-3"
];
I've tried this...
$("#parent-div > div").attr("id");
...but it only gives me the first childs id, e.g. div-no-1. I want ALL of them

An alternative to Jack Bashford's solution using $.map:
const divIds = $.map($('#parent-div > div'), div => div.id);
console.log(divIds);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
Or, using .map and .get:
const divIds = $('#parent-div > div').map((i, div) => div.id).get();
console.log(divIds);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>

Use jQuery's each and push the id to the array:
var parentDiv = [];
$("#parent-div > div").each((index, elem) => {
parentDiv.push(elem.id);
});
console.log(parentDiv);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>

If you want to do it in pure JavaScript, you can just get the children of the parent element and then loop over the result and push the ids into an array.
var children = document.getElementById("parent-div").children;
var idArr = [];
for (var i = 0; i < children.length; i++) {
idArr.push(children[i].id);
}
console.log(idArr);
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>

This can be done in plain JavaScript using document.querySelectorAll('#paren-div > div') followed by a map() and some destructuring to get the id.
const ids = [...document.querySelectorAll('#parent-div > div')].map(({ id }) => id);
console.log(ids);
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>

Give map a try
var arr = jQuery.map($("#parent-div").children(), function (d) {
return $(d).attr("id");
});
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>

You can use .querySelectorAll() with Descendant combinator
Descendant combinator The (space) combinator selects nodes that are
descendants of the first element. Syntax: A B
"#parent-id [id]" to match all child nodes having an id attribute, spread syntax to convert NodeList to Array and Array.prototype.map()
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div></div>
<div class="div-no-2-6-6"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
text
</div>
<script>
let ids = [...document.querySelectorAll("#parent-div [id]")].map(({id}) => id);
console.log(ids);
</script>

The without jquery solution :
const elements = [...document.querySelectorAll('#parent-div *[id]')];
console.log(elements.map(({ id }) => id));
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>

You can try this:
// Make an empty arary to push ids into
var arrayOfIds = [];
// Select parent element
var parentElement = document.querySelector('#parent-div');
// Select child elements
var childElements = parentElement.querySelectorAll("div");
// Push the id attribute of every child element
// Into he previousely created array
for (var i = 0; i < childElements.length; i++) {
arrayOfIds.push(childElements[i].getAttribute("id"));
}
console.log(arrayOfIds);
<div id="parent-div">
<div id="div-no-1"></div>
<div id="div-no-2"></div>
<div id="div-no-3"></div>
<div id="div-no-4"></div>
</div>
You can use .getAttribute("class") to get the CSS classes of all the elements, or any other attribute, by the same logic.

var ids = [];
$("#parent-div > div").each(function( index ) {
ids.push($(this).attr('id'));
});

Related

Wrapping elements while looping through HTMLCollection causes problem

I want to wrap each item of the container in a div. When I loop through HTMLCollection, some elements are accessed multiple times while others are left out
HTML
<div class="container">
<div class="item_1"></div>
<div class="item_2"></div>
<div class="item_3"></div>
<div class="item_4"></div>
<div class="item_5"></div>
<div class="item_6"></div>
<div class="item_7"></div>
<div class="item_8"></div>
<div class="item_9"></div>
</div>
JS
const container = document.querySelector('.container');
const items = container.children;
for(let i = 0; i < items.length; i++) {
const wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
wrapper.appendChild(items[i]);
container.appendChild(wrapper);
}
Looping directly through HTMLCollection gives this bizarre result
<div class="container">
<div class="item_2"></div>
<div class="item_4"></div>
<div class="item_6"></div>
<div class="item_8"></div>
<div class="wrapper">
<div class="item_1"></div>
</div>
<div class="wrapper">
<div class="item_5"></div>
</div>
<div class="wrapper">
<div class="item_9"></div>
</div>
<div class="wrapper">
<div class="wrapper">
<div class="item_7"></div>
</div>
</div>
<div class="wrapper">
<div class="wrapper">
<div class="wrapper">
<div class="wrapper">
<div class="item_3"></div>
</div>
</div>
</div>
</div>
</div>
problem gets solved when I convert HTMLCollection to an Array
const items = Array.from(container.children);
I can't understand what causes such behavior
You were iterating the container.children list which you were also changing during the iterations. This messed up the iteration. You can solve this, as you mentioned yourself, by converting the container.children to an array because then you are not iterating over the live container.children list but over an array copy of that. This copy is still referring to the correct child elements so they are moved correctly with the appendChild() function.
As an alternative you can use the querySelecterAll() to retrieve all the elements you want to wrap.
const container = document.querySelector('.container');
const items = container.querySelectorAll('.container > *');
for(let i = 0; i < items.length; i++) {
const wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
wrapper.appendChild(items[i]);
container.appendChild(wrapper);
}
.wrapper {
background-color: red;
}
<div class="container">
<div class="item_1">1</div>
<div class="item_2">2</div>
<div class="item_3">3</div>
<div class="item_4">4</div>
<div class="item_5">5</div>
<div class="item_6">6</div>
<div class="item_7">7</div>
<div class="item_8">8</div>
<div class="item_9">9</div>
</div>

Copy Class Values to Div

I have HTML File:
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="Function()">Whatever</button>
<div id="result"></div>
I'd like my function to take values from all four divs with class "um-field-value"
<div class="um-field-value">Value1</div>
And past them in Div "result"
Essentially, I want a script to simply copy values given in class um-field-value and paste it in a "result" div. I tried following:
function Function() {
var x = document.getElementsByClassName("um-field-value");
document.getElementsById('result').innerHTML = x;
}
But that doesn't work at all.
I am somewhat new to coding so I am not entirely sure if it is even possible. Googled for over an hour but couldn't find any solutions.
document.getElementsByClassName gets the HTML nodes themselves but then you have to extract the values from within the HTML nodes, combine them, and set that to your result div. Example snippet below:
function myFunction() {
var valueNodes = Array.prototype.slice.call(document.getElementsByClassName("um-field-value"));
var values = valueNodes.map(valueNode => valueNode.innerHTML);
var result = values.join(' ');
document.getElementById('result').innerHTML = result;
}
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="myFunction()">Whatever</button>
<div id="result"></div>
Use querySelectorAll to get all the dom with this class um-field-value and iterate over that to get the innerHTML
There is a typo in your code.It is getElementById instead of getElementsById. There is an extra s
function Function() {
var x = document.querySelectorAll(".um-field-value");
let result = '';
for (var y = 0; y < x.length; y++) {
result += x[y].innerHTML;
}
document.getElementById('result').innerHTML = result;
}
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="Function()">Whatever</button>
<div id="result"></div>
You are on the right track. document.getElementsByClassName will return a NodeList. You need to get the innerText for each of the elements in that list. Depending on the browser you can either use forEach or a regular for loop to iterate over the list.
function Function() {
var fieldsList = document.getElementsByClassName("um-field-value");
var fieldValues = [];
fieldsList.forEach(function(field) { fieldValues.push(field.innerText) });
document.getElementsById('result').innerHTML = fieldValues.join(", ");
}
This is a simple and readable solution that uses a loop to get the text inside each element and add it to a string. getElementsByClassName returns an array of all elements found, so a loop is needed to get the text inside each with textContent.
function Function() {
var result = '';
var fields = document.getElementsByClassName("um-field-value");
for (var i=0; i<fields.length; i++) {
result += fields[i].textContent + '\n';
}
document.getElementById('result').innerHTML = result;
}
<div class="um-field-area">
<div class="um-field-value">Value1</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value2</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value3</div>
</div>
<div class="um-field-area">
<div class="um-field-value">Value4</div>
</div>
<button onclick="Function()">Whatever</button>
<div id="result"></div>

Convert rows of Div values into an array with jQuery

Example:
I have a variable amount of rows, each with 3 divs with classes like so:
<div class="row>
<div class='date'>1/2/2018</div>
<div class='event'>concert</div>
<div class='act'>Pink Floyd</div>
</div>
<div class="row>
<div class='date'>12/5/2017</div>
<div class='event'>dj set</div>
<div class='act'>Moby</div>
</div>
<div class="row>
<div class='date'>5/5/2018</div>
<div class='event'>movie</div>
<div class='act'>Ant-Man</div>
</div>
How can I use jQuery to gather them into an associative array that I'll be passing to php to INSERT into a database table?
You can use map to loop thru the .row div. Use reduce to group the inner divs into a js object.
var result = $('.row').map(function() {
return $(this).find('div').toArray().reduce(function(c, v) {
c[$(v).attr('class')] = $(v).text();
return c;
}, {});
}).get();
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class='date'>1/2/2018</div>
<div class='event'>concert</div>
<div class='act'>Pink Floyd</div>
</div>
<div class="row">
<div class='date'>12/5/2017</div>
<div class='event'>dj set</div>
<div class='act'>Moby</div>
</div>
<div class="row">
<div class='date'>5/5/2018</div>
<div class='event'>movie</div>
<div class='act'>Ant-Man</div>
</div>
To select each all the div with the class row use this
var rows=$('div.row');
To loop through it use this
var array=[];
for(var i=0;i <rows.length;i++){
$.each(rows,function(){
var children=this.children('div');
$.each(children,function(){
var index=this.attr('class');
var value=this.text();
array[i][index]=value;
});
});
}
console.log(array);

create array from specific classes texts

I need to create an array from all planet text:
<div class='planet'>earth</div>
<div class='planet'>sun</div>
<div class='planet'>moon</div>
var planets = JSON.stringify(Array.from($('.planet').text()));
console.log(planets);
In console I need:
["earth","sun","moon"]
Any help?
You can simply use document.querySelectorAll to select all those elements, use Array.from to get an array, and use Array.prototype.map to generate an array from it.
console.log(Array.from(document.querySelectorAll(".planet")).map(t => t.innerText));
<div class='planet'>earth</div>
<div class='planet'>sun</div>
<div class='planet'>moon</div>
Use each function in jquery to traverse all the elements and then push in array.
planets=[]
$('.planet').each(function(){
planets.push($(this).text())
});
console.log(planets);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='planet'>earth</div>
<div class='planet'>sun</div>
<div class='planet'>moon</div>
var arr = [];
document.querySelectorAll('.planet').forEach(elem => {
arr.push(elem.textContent);
});
console.log(arr);
<div class='planet'>earth</div>
<div class='planet'>sun</div>
<div class='planet'>moon</div>
Use jQuery.each
var planets = [];
$('.planet').each((i, e) => planets.push($(e).text()));
console.log(planets);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='planet'>earth</div>
<div class='planet'>sun</div>
<div class='planet'>moon</div>

How to push element attribute value into javascript array?

This is my html structure. Here, i have created two attributes for each element. How to push attribute value into an array (like this structure, [[1,0],[1,1],[1,2],[0,2],[2,2],[1,3],[1,4]])?
<div id="demo">
<div data-floor="1" data-floor-sub="0">Div1</div>
<div data-floor="2" data-floor-sub="0">Div2</div>
<div data-floor="3" data-floor-sub="0">Div3</div>
<div data-floor="3" data-floor-sub="1">Div4</div>
<div data-floor="3" data-floor-sub="2">Div5</div>
<div data-floor="4" data-floor-sub="0">Div6</div>
<div data-floor="5" data-floor-sub="0">Div7</div>
</div>
Use map()
var multiDimArray = $('#demo div').map(function() {
var innerArray = [];
innerArray.push([$(this).data('floor'), $(this).data('floor-sub')]);
return innerArray;
}).get();
console.log(multiDimArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="demo">
<div data-floor="1" data-floor-sub="0">Div1</div>
<div data-floor="2" data-floor-sub="0">Div2</div>
<div data-floor="3" data-floor-sub="0">Div3</div>
<div data-floor="3" data-floor-sub="1">Div4</div>
<div data-floor="3" data-floor-sub="2">Div5</div>
<div data-floor="4" data-floor-sub="0">Div6</div>
<div data-floor="5" data-floor-sub="0">Div7</div>
</div>

Categories

Resources