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());
});
Related
I'm trying to order the different products from a website but can't do it correctly.
Basically I need to get the price of each one and order them from the most expensive one to the least one.
I tried the following code but it disappears everything and keeps not ordering them in the correct way:
var divList = $(".block-level.h2");
divList.sort(function(a, b){
return $(a).data(".block-level.h2")-$(b).data(".block-level.h2")
});
$(".grid").html(divList);
I don't have access to modify the HTML so it has to be done with the code I have now, only can add things through jQuery.
Can someone give me a tip or help me out please?
Thank you.
For your request to sort the product grid items, here is the jQuery code that you can use.
var values = [];
$('.block-level.h2').each(function() {
var temp = Array();
temp['value'] = parseInt($(this).html().replace('$',''));
temp['element'] = $(this).closest('.grid-item');
values.push(temp);
});
values.sort(function(a,b) { return b.value - a.value; });
var sortedHtml = '';
$.each(values, function(index, obj) {
if((index+1)%3==1) {
sortedHtml+=('<div class="grid product-cards__row"><div class="grid-item one-third palm-one-whole product-cards__item">'+$(obj.element).html()+'</div>');
} else if((index+1)%3==0) {
sortedHtml+=('<div class="grid-item one-third palm-one-whole product-cards__item">'+$(obj.element).html()+'</div></div>');
} else {
sortedHtml+=('<div class="grid-item one-third palm-one-whole product-cards__item">'+$(obj.element).html()+'</div>');
}
});
$('.product-cards').html(sortedHtml);
Hope this helps!
You can achieve this by the following code-
var values = Array();
$('.block-level.h2').each(function() {
values.push(parseInt($(this).html().replace('$','')));
});
values.sort(function(a, b){return b-a});
In your code above - the main problem is with $(a).data(".block-level.h2") since its trying to find an attribute with name data-.block-level.h2 in element a which doesn't exist. That's why the empty result.
I need to find all elements in a page by attribute value only (ignoring the key) using jquery.
Is there a way to do this easily?
Currently, I am just iterating on all elements in the page, on every property etc..
You can use $.expr, Element.attributes, Array.prototype.some()
$.expr[":"].attrValue = function(el, idx, selector) {
return [].some.call(el.attributes, function(attr) {
return attr.value === selector[selector.length - 1]
})
};
// filter element having attribute with `value` set to `"abc"`
$(":attrValue(abc)").css("color", "blue");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div title="abc">abc</div>
<div title="def">def</div>
<div title="ghi">ghi</div>
<div title="jkl">jkl</div>
Use brackets []
var ElementsWithAttributeKeyTest = $('[attributeKey="Test"]');
Or pass an object with the attribute name and value as parameter to this function:
var getElemsByAttribute = function(obj) {
if (obj) {
if (obj.attributeKey && obj.attributeValue) {
return $('[' + obj.attributeKey + '="' + obj.attributeValue + '"]');
}
}
}
var attrObj = {
attributeKey: 'data-color',
attributeValue: 'red'
}
getElemsByAttribute(attrObj).css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span data-color="red">Red</span>
<span data-color="red">Red</span>
<span data-color="green">Green</span>
<span data-color="blue">Blue</span>
<span data-color="red">Red</span>
<span data-color="green">Green</span>
If you want to search all attributes values you can use this small plugin:
$.fn.search_by_attr_value = function(regex) {
return this.filter(function() {
var found = false;
$.each(this.attributes, function() {
if (this.specified && this.value.match(regex)) {
found = true;
return false;
}
});
return found;
});
};
and you can use it like this:
$('*').search_by_attr_value(/^some value$/);
Based on this answer
You could define new function take as parameter the value you want to filter with (e.g get_elements_by_value(filter)), then inside this function parse all the elements of the page using $('*').each(), after that parse the attributes of every element el of those elements using attribute attributes like below :
$.each(el.attributes, function(){ })
Then inside the each loop you could make your condition and push the matched values with the passed filter inside matched[] that should be returned.
Check working example below, hope this helps.
function get_elements_by_value(filter){
var matched=[];
$('*').each(function(index,el) {
$.each(el.attributes, function() {
if( this.value===filter )
matched.push(el);
})
})
return $(matched);
}
get_elements_by_value('my_value').css('background-color','green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div title="my_value">AA</div>
<div title="def">BB</div>
<input type='text' name='my_value' value='CC'/>
<p class='my_value'>DD</p>
<span title="test">EE</span>
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();
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>
I'm creating a set of tabs based upon an existing set of categories with the below JS. I need to extend this to target specific id's within the DIV id based upon values from a JS array.
$("#categories div[id^=category]:not(:first)", this).hide();
var cats = $('#categories div[id^=category]');
cats.each(function () {
var anch = $(this).find('h3 a').eq(1).clone();
anch[0].rel = this.id;
$('<li/>').append(anch).appendTo('#tabs');
});
The html:
<div id="category_1">
<h3 class="maintitle">
<a class="toggle">..</a>
Cat 1 Title
</h3>
<div>
...
</div>
</div>
<div id="category_2">
<h3 class="maintitle">
<a class="toggle">..</a>
Cat 2 Title
</h3>
<div>
...
</div>
</div>
I've got a JS array ready by adding:
var catsList = '{$cats}'; // comma separated list of numbers generated in PHP - returns 1,4,8 currently.
var catsArray = catsList.split(',');
How would I convert the below, to check for each item within catsArray ?
var cats = $('#categories div[id^=category]');
Something like
var cats = $('#categories div[id^=category_'+catsArray+']');
but obviously checking each item within the array and not the entire array as that's doing.
You could use that as IDs have to be unique on context page:
var cats = $('#category_'+catsArray.join(',#category_'));
DEMO
you probably want the each function
$.each(catsArray,function(index, item) {
var cats = $('#categories div[id^=category_'+item+']');
});
Depending on how you using this a for loop will do it also:
for (var i = 0; i < catsArray.length; i++) {
var catIndex = catsArray[i];
var cats = $('#categories div[id^=category_'+catIndex +']');
}