what I'm trying to do is iterate over a collection of div, contained in a parent container. My structure is the following:
<div id='main'>
<div data-id='2'>
</div>
<div data-id='3'>
</div>
</div>
My goal is take the field data-id of each div and create an array collection. Previously I used the select where do I get each value of available option, like this:
var available_services = $('#selected-service').find('option', this).map(function ()
{
return this.value;
}).get();
But now I'm using a div collection instead of the select. How I can iterate through all available div?
This should return all data-id values in a list:
var available_services = $('#main').find('div').map(function (item)
{
return item.attr('data-id');
});
I didn't test this, but I think should do the job. (maybe you need to tweak a little bit)
I believe this will do it:
var available_services = [];
$('#main div').each(function(){
available_services.push($(this).data( "id" ));
})
This is the easy way to go:
$(document).ready(function() {
var myCollection = [];
$('#main div').each(function(){
var dataDiv = $(this).attr('data-id');
myCollection.push(dataDiv)
})
});
Try this:
(function(){
var main = $("#main");
var divs = $(main).find("div");
var arrId = divs.map(function(index, div){
return $(div).attr("data-id");
});
console.log(arrId);
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='main'>
<div data-id='2'>
</div>
<div data-id='3'>
</div>
</div>
Related
I have HTML like this:
<div class="foo">
<div class="bar1">A</div>
<div class="bar2">B</div>
<div class="bar3">C</div>
</div>
<div class="foo">
<div class="bar1">D</div>
<div class="bar2">E</div>
<div class="bar3">F</div>
</div>
<div class="foo">
...etc.
I am trying to iterate through the "foo" divs to create objects like {bar1: A, bar2: B, bar3: C} with code sort of like this:
var arrayOfObjects= [];
var rows = $(".foo");
for (var i=0; i<rows.length; i++) {
var row = rows[i];
arrayOfObjects.push(
{
bar1: row.find(".bar1").text(),
bar2: row.find(".bar2").text(),
bar3: row.find(".bar3").text()
}
);
}
I understand that this doesn't work because the original var rows = $(".foo"); creates an array of DOM elements, which don't have find() as a function. I also know that within the loop, I could start using elementByClass and innerHtml, but I feel like my brain starts crying whenever I start mixing jQuery-style and DOM-style selectors in the same code.
Is there a way to fix my code above so that I'm using jQuery selectors within the loop?
You can wrap your elements as jQuery objectslike this:
arrayOfObjects.push(
{
bar1: $(row).find(".bar1").text(),
bar2: $(row).find(".bar2").text(),
bar3: $(row).find(".bar3").text()
}
);
This makes you row a JQuery object, which has the 'find' method.
You can easily iterate through .row divs by using each(),
var arrayOfObjects= [];
$(".foo").each(function(){
var items = {"bar1" : $(this).find('.bar1').text(),"bar2" : $(this).find('.bar2').text(), "bar3" : $(this).find('.bar3').text()};
arrayOfObjects.push(items); //If you want to push all into an object and then into an array
//or to use it on its own
$(this).find('.bar1').text();
$(this).find('.bar2').text();
$(this).find('.bar3').text();
});
Hope this helps.
//find all the foo, and map them into new elements
var result = $('.foo').map(function(index, element){
//we want to map all the children of the element into a single object
return $(element).children().get().reduce(function(aggregate, childElement){
//get the class off of the child and it's value, put them in the object
aggregate[childElement.className] = childElement.innerText;
return aggregate;
}, {}); //second argument to the reduce() is the starting element
}).get(); //use get() to break the array out of the jQuery object
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<div class="bar1">A</div>
<div class="bar2">B</div>
<div class="bar3">C</div>
</div>
<div class="foo">
<div class="bar1">D</div>
<div class="bar2">E</div>
<div class="bar3">F</div>
</div>
$(document).ready(() => {
var arrayOfObjects = $('.foo').map(function() {
return $(this).find('>*').map(function(obj) {
return {
class: $(this).attr('class'),
text: $(this).text()
};
}).get().reduce( (obj, arr) => {
obj[arr.class] = arr.text;
return obj;
}, {});
}).get();
console.log(arrayOfObjects);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<div class="bar1">A</div>
<div class="bar2">B</div>
<div class="bar3">C</div>
</div>
<div class="foo">
<div class="bar1">D</div>
<div class="bar2">E</div>
<div class="bar3">F</div>
</div>
hope this helps you :)
Something along these lines with .each would probably work
const $rows = $('.foo');
let arrayOfObjects = [];
$rows.each(function(i) {
const $row = $(this);
let obj = {};
$row.children().each(function(ch) {
obj = { ...obj, [this.className]: $(this).text() };
});
arrayOfObjects = [ ...arrayOfObjects, obj ];
});
console.log(arrayOfObjects);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<div class="bar1">A</div>
<div class="bar2">B</div>
<div class="bar3">C</div>
</div>
<div class="foo">
<div class="bar1">D</div>
<div class="bar2">E</div>
<div class="bar3">F</div>
</div>
Consider the following snippet as an example:
<div class="bar foo">
</div>
<div class="bar">
<div class="foo"></div>
</div>
Given var $set=$('.bar'); I need to select both nodes with foo class. What is the proper way to achieve this. Considering addBack() requires a selector and here we need to use the $set jQuery object and $set.find('.foo') does not select the first node.
use this :
var $set = $(".bar").filters(function () {
var $this = $(this);
if($this.is(".foo") || $this.find(" > .foo").length !== 0){
return true;
} else{
return false;
}
});
Here's one way of going about it:
var set = $('.bar');
var foos = [];
for (var i = 0; i < set.length; i++) {
if ($(set[i]).hasClass('foo')) {
foos.push(set[i]);
}
}
if (set.find('.foo').length !== 0) {
foos.push(set.find('.foo')[0]);
}
console.log(foos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bar foo"></div>
<div class="bar">
<div class="foo"></div>
</div>
The for loop checks all elements picked up with jQuery's $('.bar'), and checks if they also have the foo class. If so, it appends them to the array. The if checks if any of the elements picked up in set have any children that have the foo class, and also adds them.
This creates an array that contains both of the DIVs with the foo class, while excluding the one with just bar.
Hope this helps :)
test this :
var $newSet = $set.filter(".foo").add($set.has(".foo"));
You could use the addBack() function
var $set=$('.bar');
console.log($set.find(".foo").addBack(".foo"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bar foo">
</div>
<div class="bar">
<div class="foo"></div>
</div>
I have a bunch of spans of class = "change" and each has a unique id. I created an array of those spans using:
var changesArray = $('.change').toArray()
I want to be able to get the index of the span in the array when I click on it. I tried:
$('.change').click(function(){
var thisChange = $(this).attr('id');
var thisChangeIndex = $.inArray(thisChange,changesArray);
});
But all I get is -1 for every .change I click on.
I'm a bit of a newbie with this type of code. Help?
The toArray method says
Retrieve all the elements contained in the jQuery set, as an array.
You are looking for a particular id in the array - that will never work.
If you want the index of the item you can use .index()
$('.change').click(function(){
var thisChangeIndex = $('.change').index(this);
console.log(thisChangeIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="change">change1</span>
<span class="change">change2</span>
<span class="change">change3</span>
<span class="change">change4</span>
</div>
<div>
<span class="change">change5</span>
<span class="change">change6</span>
<span class="change">change7</span>
<span class="change">change8</span>
</div>
You should keep a plain array of the unique ID's only:
var changesArrayIds = $('.change').toArray().map(function(x) { return x.id; });
Then this line should work fine:
var thisChangeIndex = $.inArray(thisChange, changesArrayIds);
If you insist on using .toArray that works http://codepen.io/8odoros/pen/JKWxqz
var changesArray = $('.change').toArray();
$('.change').click(function(){
var thisChange = $(this).attr('id');
var thisChangeIndex = -1;
$.each( changesArray, function( i, val ) {
if( thisChange==val.id) thisChangeIndex= i;
});
console.log(thisChangeIndex);
});
When you call toArray, you get an array of all the DOM nodes, not the jquery objects. You can search on this instead of $(this):
var changesArray = $('.change').click(function(){
var thisChangeIndex = $.inArray(this,changesArray);
}).toArray();
I add a data attribute to an element via jquery data() function.
I want to use find() function to get the element. But obviously, it does not work.
What I want to do is caching the element's parent element and do a lot of things.
Like this:
var $parent = $('#parent');
var $dataElement = $parent.findByData('whatever');
$parent.xxx().xxx().xxx()....;
I don't want this:
var $parent = $('#parent');
var $dataElement = $("#parent [data-whatever='whatever']");
$parent.xxx().xxx().xxx()....;
//It looks like find the parent twice.
Can any function do this?
I add a data attribute to an element via jquery data() function.
As you mentioned you are setting the data to the element with data() method of jQuery. Which doesn't adds any attribute in the DOM. So you can't find it with .find() that way because it's in memory*.
Instead you should use .attr() method to set the data attribute and then you can read it from the DOM with .find() method.
* don't have proper word for it
below is an example of setting the data with .data() and trying to find it.
$('#parent').find('.two').data('test', 'myTest');
var div = $('#parent').find('.child[data-test="myTest"]').length;
alert(div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<div class='child one'></div>
<div class='child two'></div>
</div>
below is an example of setting the data with .attr() and trying to find it.
$('#parent').find('.two').attr('data-test', 'myTest');
var div = $('#parent').find('.child[data-test="myTest"]').length;
alert(div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<div class='child one'></div>
<div class='child two'></div>
</div>
below is an example as per your comment:
$('#parent').find('.two').data('test', 'myTest');
var div = $('#parent').find('.child').filter(function(){
return $(this).data('test') == 'myTest'
}).text();
console.log(div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<div class='child one'>One</div>
<div class='child two'>Two</div>
</div>
You can try $(child,parent) way and attribute selector $('[attribute-name]') as parameter,
var $parent = $('#parent');
var $dataElement = $parent.children().filter(function(){
return $(this).data('whatever') !== undefined
});
If you need a function findByData(),
$.fn.findByData = function(dataAttribute){
return $(this).children().filter(function(){
return $(this).data(dataAttribute) !== undefined
});
}
var $parent = $('#parent')
var $dataElement = $parent.findByData('whatever');
Fiddle Demo
If you want to get the parent element only when it has data attribute value equals to somevalue, you need to use filter function:
$parent.filter(function(){
return $(this).data('whatever') == "whatever"
});
If you want to find child element of parent that has data attribute value equals to somevalue:
$parent.find("*").filter(function(){
return $(this).data('whatever') == "whatever"
});;
<div id="parent">
<p data-whatever='whatever'>Whatever1</p>
<p data-whatever='whatever'>Whatever2</p>
<p data-whatever='whereever'>Whereever1</p>
</div>
var $parent = $('#parent');
var $dataElements = $parent.find("*[data-whatever='whatever']");
This will return an array of decedent elements inside the "#parent" element having data-whatever='whatever'.
$.each($dataElements,function(key,val){
console.log( $($dataElements[key]).html());
});
Demo
I have some HTML:
<div id="bin">
<span class="item1 selectMe">1</span>
<span class="item2 selectMe">2</span>
<span class="item3 dontSelectMe">3</span>
</div>
I would like to return an array with the values in the span elements which contain the selectMe class. This is what I've written:
var values = [];
$('#bin span.selectMe').each(function() {
values.push($(this).text());
});
However, when I print values to the console, it is always empty. Any thoughts on why I am not iterating through the bin?
What you have should work, but here is a more elegant solution:
var values = $('#bin span.selectMe').map(function() {
return $(this).text();
}).get();
The following should work, however what you paste above should seem to also:
var values = $('#bin span.selectMe').map(function(){
return $(this).html();
});
var values = [];
$('#bin').find('span.selectMe').each(function() {
values.push($(this).text());
});