How to find all the id's associated with a particular class - javascript

Using jquery how is it possible finding out all the id's associated with a given class?
Any help??

Loop over all of the elements with the specified class, and store their IDs in an array. See jQuery .each
var ids = [];
$('.class').each(function() {
if($(this).attr('id'))
ids.push($(this).attr('id'));
});

Try this
Live Demo
//This will give you ids of all the controls have the specified class
$('.className').each(function(){
alert(this.id);
});

Using jQuery:
var ids = $(".class").map(function() {
return this.id.length > 0 ? this.id : null;
}).get();
Checking if the id.length > 0 makes sure you don't empty strings from elements without an id.
DEMO: http://jsfiddle.net/T8YuD/

You could use them together like $('#id.class').

function getIDs(className)
{
var ids = [];
$('.' + className).each(function()
{
var id = $(this).attr('id');
if (id) ids.push(id);
});
return ids;
}

function getAllIds(className){
var results = [];
$(className).each(function(){
results.push($(this).attr('id'));
});
return results;
}

Related

Get all Select elements on the page with value set to foo

I have several <select> inputs on my page.
Using jQuery, how can I get all <select> elements with the selected option equal to "foo"? (Keeping the result as a jquery set, so I can traverse from each element in it)
I've tried the following, but this always seems to return an empty array.
$('option[selected][value="foo"]');
You may try this (Example) :
var sel = $('select').filter(function(){
return $(this).val() == 'foo';
}).get();
$(document).ready(function() {
var data = [];
$('select').each(function(index) {
if(this.selectedIndex) {
if(this[this.selectedIndex].value == 'foo') {
data.push(this[this.selectedIndex]);
}
}
});
console.log(data);
});
http://jsfiddle.net/G2szE/
$('select option[value="foo"][selected="selected"]').parent()
If you want to select all "select" tags and their respective values in Javascript then use this code:
var tag =document.querySelectorAll("select");
var values="";
for(var i=0; i<3; i++) {
values+= i+"="+tag[i].value+",";
}
alert(values);
Replace the number of values with array.length.

jQuery, search for element with value in attribute among the matched elements

I find a collection of a tags using jQuery like this:
itemsPresent = $('h3.zn-ItemTitle > a');
Later in my scripts I need to find the a within the matched elements with a specific url in its href attribute without making a new jQuery select.
How can I do this?
You can use the attribute equals selector:
itemsPresent = $('h3.zn-ItemTitle > a[href="http://your-url.com"]');
Alternatively, if you want to keep them as separate objects:
var itemsPresent = $('h3.zn-ItemTitle > a'),
filteredAnchors = itemsPresent.filter('[href="http://your-url.com"]');
Use .filter() to filter the Jquery object based on your desired conditions.
Try,
itemsPresent.filter(function(){
return $(this).attr('href') == 'something';
})
Or as BenM suggested you can use,
itemsPresent.filter('[href="something"]');
You can filter the collection
itemsPresent = $('h3.zn-ItemTitle > a');
var otherItems1 = itemsPresent.filter('[href="someUrl"]');
//or
var otherItems2 = itemsPresent.filter(function() {
return this.href.indexOf('someURL') != -1;
});
You can use filter:
var $a = itemsPresent.filter(function() {
return $(this).prop('href') == 'http://your-website.com';
});

Getting the val for all check boxed with a class

Trying to get all checkboxes with the class 'testclass' to check if they are checked, if so, add their value to theString.
$('.testclass').each(function () {
if (this.checked) {
var x = this.val();
theString += x + ";";
}
});
It seems to be getting stuck at the part where it gets the val?
You can use :checked with class .testclass to get the checked elements with specific class:
$('.testclass:checked').each(function() {
console.log(this.value)
});
just seen the code and it seems that your problem is this:
this.val();
try changing either to this:
this.value
or
$(this).val(); //<---------jQuery version
Your Problem
The problem with your code is this is a DOM element and not a jQuery object. You would need to change
var x = this.val();
to
var x = this.value;
//or
var x = $(this).value; //slower
Better solution
You can use :checked in your selector to get the checkboxes that are selected. You can than use map() to get the values.
var values = $(".testclass:checked") //get the checked checkboxes
.map(function () { //Map loops through each element in the jQuery object produces a new jQuery object containing the return values.
return this.value;
})
.get() //gets the newly created array
.join(","); //joins the array with commas as a seperator
using $.map
try this
var theString=$('.testclass:checked').map(function(n){
return this.value;
}).get().join(','); //get the checked value and join it with ,
alert(theString);
theString will have all the checked values commaseperated...
Try below code for get all checked checkbox value
$('.testclass:checked').each(function () {
var x = this.val();
theString += x + ";";
});
Try
var values = $('.testclass:checked').map(function(idx, el) {
return $(el).val()
}).get();
Not using jQuery :
checkedList = [].slice.call (document.querySelectorAll ('.testclass:checked'))
.map (function (el) { return el.value; })
.join (';');
Demo at http://jsfiddle.net/jstoolsmith/AeXWs/
Please have a look at http://jsfiddle.net/2dJAN/54/
$('.check').on("click",function(){
$.each($('.testclass'), function(){
if($(this).is(':checked')){
alert($(this).val());
}
});
});
try
$('.testclass:checked').each(function() {
alert(($(this).value))
});
var theString = "":
$('.testclass').each(function () {
if ($(this).checked) {
theString += $(this).val()+";";
}
});
UPDATE: My bad, missed the part of question, where you needed values too.

Populate a javascript array with links of a specific class

I'm looking to take a website source and populate an array with a collection of links, filtered by their a class.
Say, for instance, the links were <a class="title">, how could I target each class and add the URL to an array?
Would Javascript or jQuery work better?
var arr = new Array();
$("a.title").each(function()
{
arr.push($(this).attr("href"));
});
So, basically you create an array by using the Array constructor. Then you use JQuery's each method to iterate over the links with class title, getting their urls using the attr method and pushing them in the array along the way.
It's pretty easy with jQuery:
var arr = [];
var ptr = 0;
$('.title').each(function() {
arr[ptr] = $(this).attr('href');
ptr++;
})
Something like
var collectionOfLinks = {};
$('a').each(function() {
var cl = $(this).attr('class');
if (collectionOfLinks[cl] === undefined) {
collectionOfLinks[cl] = [];
collectionOfLinks[cl].push($(this).attr('href'));
}else{
collectionOfLinks[cl].push($(this).attr('href'));
}
});
With this you end up with an object whose properties names are the classes of the <a> elements and whose values are arrays of href
With jQuery, you can do var urls = $("a.title").attr("href")to get what you want.
You can do something like below,
var linkURL = [];
$('a.title').each (function () {
linkURL.push(this.href);
});

jQuery Selecting Elements That Have Class A or B or C

I working on something where I need two functions.
1 - I need to look at a group of children under the same parent and based on a class name, "active", add that element's ID to an array.
['foo-a','foo-b','foo-d']
2 - I then iterate through all the children in another parent and for each element I want to find out if it has any class name that match the ids in the array.
Does this element have class foo-a, foo-b or foo-d?
For the first part, I'd use map and get:
var activeGroups = $('#parent .active').map(function() {
return this.id;
}).get();
This gives you an array of id values (say, ['foo-a', 'foo-d']). You can then make a selector like .foo-a, .foo-b, .foo-c (the multiple selector) using join:
var activeSelector = '.' + activeGroups.join(', .');
This makes a valid jQuery selector string, e.g. '.foo-a, .foo-d'. You can then use this selector to find the elements you want using find:
var activeEls = $('#secondParent').find(activeSelector);
You can then do whatever you need to with activeEls.
var active = $("#foo").find(".active").map(function() {
return this.id;
}).get();
$("#anotherParent *").each(function() {
var that = this;
var classes = $(this).attr("class");
if(classes.indexOf(" ") !== -1) {
classes = classes.split(" ");
} else {
classes = [ classes ];
}
$.each(classes, function(i, val) {
if($.inArray(val, active)) {
// this element has one of 'em, do something with it
$(that).hide();
}
});
});
There's always .is('.foo-a, .foo-b, .foo-d'). Or if you actually just wanted to select them, instead of iterating and deciding for each element, $('.foo-a, .foo-b, .foo-d', startingPoint).

Categories

Resources