create array from specific classes texts - javascript

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>

Related

get ALL id's of children elements

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

Add JS array values to multiple divs

I have an array
var arr = [3,0,1,0,0];
and multiple divs.
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>
and more.
How to add values from an array alternately by numbers in an array to div numbers by classes.
<div class="fb0">3</div>
<div class="fb4">0</div>
<div class="fb2">1</div>
<div class="fb3">0</div>
<div class="fb1">0</div>
You can use jQuery's .each() to loop through all the div. Inside event handler function use the index to take the item from the array and set the text of the current element:
var arr = [3,0,1,0,0];
$('[class^=fb]').each(function(idx){
if(arr.length >= idx) // check if the array length is grater/equal to the current index.
$(this).text(arr[idx]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>
JavaScript solution with Document.querySelectorAll() and Array.prototype.forEach():
var arr = [3,0,1,0,0];
var elements = [].slice.call(document.querySelectorAll('[class^=fb]'));
elements.forEach(function(div, idx){
if(arr.length >= idx) // check if the array length is grater/equal to the current index.
div.textContent = arr[idx];
});
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>
You can use querySelectorAll to select the div's and than using forEach you can add the values to each div accordingly.
function update(){
let arr = [3,0,1,0,0];
let divs = document.querySelectorAll('[class^=fb]')
divs.forEach((e,i)=>{
e.innerHTML = arr[i]
})
}
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>
<button onClick=update()>Click me to see output</button>

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

Extract values from attribute selector

I'm new to jQuery selectors. How can I extract the values from an attribute?
Given:
<div class='container'>
<div class='entry' data-name='foo'></div>
<div class='entry' data-name='bar'></div>
<div class='entry' data-name='baz'></div>
</div>
I'd want to extract:
['foo','bar','baz']
You can use .map() to create an array from a set of dom elements like
var array = $('.container .entry').map(function () {
return $(this).data('name')
}).get();
try this
$(function () {
var array = [];
$(".entry").each(function () {
array.push($(this).data("name"));
});
console.log(array);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='entry' data-name='foo'></div>
<div class='entry' data-name='bar'></div>
<div class='entry' data-name='baz'></div>
</div>
Try
var name = [];
$('div.container').children().map(function() {
name.push($(this).data('name'));
});
Working DEMO

Get div IDs inside a div via jquery

How do I get the IDs of all the child(1,2,3 etc.) inside the parent1 and put them into an array with jquery.
Just as info, I have a lots of "parents" (parent1, parent2 etc.)
<div id="parent1">
<div id="child1" class="child">
<div id="baby1" class="baby">TEXT</div>
</div>
<div id="child2" class="child">
<div id="baby2" class="baby">TEXT</div>
</div>
<div id="child3" class="child">
<div id="baby3" class="baby">TEXT</div>
</div>
</div>
This is my code:
var save_array = [];
$('#parent1').find("div",'.child').each(function(){ save_array.push(this.id); });
But when I do this, I get the the "baby" too.
You can use .map()
var arr = $('#parent1').find("div.child").map(function () {
return this.id;
}).get();
console.log(arr); //["child1", "child2", "child3"]
DEMO
Use this :
var save_array = [];
$('#parent1').children().each(function(){
save_array.push(this.id);
});
.find() will go through all descendants. Use .children() instead.
Try this
var save_array = [];
$("[id*='parent']").find("div.child").each(function(){
save_array.push(this.id);
});
I think the correct syntax is like this:
$('#parent1').find("div.child").each(function(){
save_array.push(this.id);
});

Categories

Resources