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
Related
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'));
});
There are several divs on the page with class "wrap-me".
I want add an element "add-me" after "wrap-me", and doubly wrap the two in a "wrapper-inner" and "wrapper".
Basically - it should look like this:
<div class="wrapper">
<div class="wrapper-inner">
<div class="wrap-me"></div>
<div class="add-me"></div>
</div>
</div>
This is my implementation:
const $addMe = $("<div>", { class: "add-me" });
const $wrapper = $('<div>', { class: "wrapper" });
const $wrapperInner = $('<div>', { class: "wrapper-inner" });
$.each($(".wrap-me"), (i, wrapMe) => {
const $wrapMe = $(wrapMe);
$wrapMe.wrap($wrapper).wrap($wrapperInner);
$addMe.insertAfter($wrapMe);
});
Here's the output:
<div class="wrapper">
<div class="wrapper-inner">
<div class="wrap-me"></div>
</div>
</div>
It's almost there, the only thing is that the "add-me" is not getting inserted into the DOM. What's wrong?
//get the template
var wrapperTemplate = $('#wrapperTemplate').text();
$('.wrap-me').each(function(index, element){
//create a new element to put in the DOM
var $wrapper = $(wrapperTemplate);
//put the wrapper after the element we are going to replace
$wrapper.insertAfter(element);
//move the element into the wrapper where it should be
$wrapper.find('.wrapper-inner').prepend(element);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap-me">A</div>
<div class="wrap-me">B</div>
<div class="wrap-me">C</div>
<div class="wrap-me">D</div>
<!-- HTML template for what we want to add, so it's not in the javascript -->
<script type="text/html" id="wrapperTemplate">
<div class="wrapper">
<div class="wrapper-inner">
<div class="add-me"></div>
</div>
</div>
</script>
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>
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 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);
});