Is it possible with jQuery to select all "IDS" of a specific block at the same time? I know that you can specify for example $('div') but I would like to select the ID's in my object. Is there an easy way to do this in jQuery? Something like:
$object = $('.wrapper');
$object.find(function(){
//GET ALL THE IDS..somehow?!
});
I'm a little curious of its purpose, but you could try this:
var ids = $('[id]', $object).map(function() {
return this.id;
});
It uses $object to provide the context for your selector, finds all elements within said context that have an id attribute, and then builds an array of the id values.
FYI, the resulting ids variable is a jQuery array-like object. If you just want a plain JS array, add a .get() after the map function:
var ids = $('[id]', $object).map(function() {
return this.id;
}).get();
// ^
jsFiddle Demo
$object.find('[id]').each(function(){
//this.id is your man
});
Related
I have an array of elements which I want to maintain efficiently, adding and removing arrays of elements over time.
var myElements = $('.initial');
jquery's merge() seems perfect for adding items as it doesn't create a new array and just adds to the existing one:
$.merge(myElements, $('.to-add'));
Is there an equivalent for removing, that also modifies the array in-place? Something like:
$.exclude(myElements, $('.to-remove'));
I do actually have arrays of DOM elements, and the selectors are just used as examples.
Assuming that you're after the relative complement of b in a.
And you don't want to create additional objects while process.
The function is for both plain Array and jQuery set.
(thus used $.each, $.inArray instead of Array.prototype.forEach Array.prototype.indexOf)
I wrote a function that fits your requirement.
$.exclude = function(a,b) {
var idx;
$.each(b, function(i, val) {
while((idx = $.inArray(val, a)) !== -1) {
a.splice(idx, 1);
}
})
return a;
}
test this code here
https://jsfiddle.net/happyhj/uwd4L1dm/8/
and you can use like this.
$.exclude(myElements, $('.to-remove'));
use jquery not method,
var filtered = $(myElements).not($('.to-remove'));
You can use delete to remove an element from an array and then use $.grep to remove the empty space.
//[0] since $("#id") will be a jquery Object
//[0] will return the particular DOM element
var orgArray = [$("#merge1")[0],$("#merge2")[0],$("#merge3")[0]];
var secArray = [$("#merge4")[0],$("#merge5")[0]]
// Will merge other two values;
// jQuery merge will merge contents of
//two array into first array
var merArray = $.merge(secArray, orgArray);
// Want to remove $("#merge2");
var getIndex = merArray.indexOf($("#merge2")[0]);
if(getIndex >-1){
delete merArray[getIndex]
}
// length before filtering
$("#l1").text(merArray.length);
//Now will remove Empty Space
merArray = $.grep(merArray,function(n){
return n==0 || n
});
$("#l2").text(merArray.length);
JSFIDDLE
You are using methods that are meant for array literals. jQuery already has method add() which will return a modified jQuery object that includes the elements matching the selector
var myElements = $('.initial');
var newCollection = myElements.add('.to-add');
newCollection.not('.to-remove').doSomething();
Don't think of jQuery objects as arrays although they are array like.
Reference add()
It's not clear what your overall objective really is but most likely you can manage it with any number of filtering methods that already exist within the api
I'm selecting html elements
var elements = $('*[my-elem="false"]');
since each element has attribute id with some value I want inside iteration to get id of currently iterated element, so I tried
$.each(elements, function(index, item){
var itemId = item.attr("id").val();
});
but I'm getting following error
TypeError: item.attr is not a function
Try console.log(item). You should see that it's a regular HTML element -- not a jQuery object.
Note that .val() refers specifically to the value attribute of an element.
Both of those in mind, if your goal is to get the ID, you can use item.id, this.id, or $(item).attr("id").
.attr is a jQuery method, so you need to use your element as if it were a jQuery selector. Also, you don't need .val for .attr('id'), so this should work
var itemId = $(item).attr("id");
it is as simple as
var itemId = item.id;
item is a DOM element, attr is a jQuery function, so you just have to wrap it in the jQuery notation var itemId = $(item).attr('id').val();
You are using the wrong version of each when looping over DOM elements. Use this one. (https://api.jquery.com/each/)
elements.each(function(index){
var itemId = $(this).attr('id').val();
});
Try
var elements = $('selector');
elements.each(function() {
alert($(this).attr('id'));
});
var itemId = this.id;
will also work
I am trying to do a each loop and generate the class names to write the text stored in the array dynamically instead of doing them one by one. Nothing seems to write to the paragraphs though?
var user = {};
user['fname'] = 'Hello';
user['lname'] = 'World';
$.each(user, function(key, value) {
$('p').hasClass(key).text(value);
});
.hasClass() returns a boolean. It returns whether any of the elements in the collection have that class.
What you want to do is create a selector that searches for that class. Something like this:
$('p').filter('.'+key).text(value);
Or even this:
$('p.'+key).text(value);
Is it possible to call a function on specific index value of nodelist which is storing div like following :
var txtElem = txtdiv.getElementsByTagName("div");
the thing i want is that i am storing list of divisions in txtElem nodelist now i want to call a function on click event of the 3rd div stored in nodelist. The divisions are created dynamically and they don't have any id so they are not accessible by id.
from what you asked, it seems like this will do:
function toPseudoArray(nodeList) {
var ar = [];
for(var i in nodeList)
if(nodeList[i].nextSibling) // or for that case any other way to find if this is an element
ar.push(nodeList[i]);
return ar;
}
Pass your nodeList to this function, use what it returns as an array that contains your elements, and only your elements.
By the way, you could directly call function on a specific element simply using my_fab_function(txtElem[0]); -- of course, until you don't exceed the count.
The question is quite unclear. Seeing the jQuery tag, these come to my mind:
A way to call a jQuery function on a specified index using .eq():
var n = 1; //the index you need
$(txtElem).eq(n).css('color', 'red');
Simple Javascript to get the DOM element:
var n = 1; //the index you need
var elem = txtElem[n]; //elem will hold the DOM element
//call simple DOM methods on it:
var s = elem.innerHTML;
//you can also call jQuery functions on it:
$(elem).css('color', 'red');
By the way txtElem is not an object, it is a NodeList, an "array-like object".
Can anyone explain me how to do this, jquery's api is really lacking on this. What is wrong in the following code?
var arr = $(value).filter(function() { return $(this).is("TD"); } ).html();
alert(arr[1]);
I just want to grab the innerHTML/text of the td and put it in an array
Using .map() with .get() is one way to go:
var arr = $(value).map(function() {
var $th = $(this);
if($th.is("TD")) return $th.html();
}).get();
alert(arr);
I'm not sure what value represents, but if you change the selector to match only td elements, you could simplify the return statement with return $(this).html();.
.map() iterates over the elements, and adds the return value to the jQuery object. .get() retrieves just the array out of the jQuery object.
http://api.jquery.com/map/
http://api.jquery.com/get/
Sounds like value is a tr. Then you could do this:
var arr = $(value).children('td').map(function() {
return $(this).html();
}).get();
alert(arr);
To create an array with each item containing an array of that row's td element's html, you could do this:
var arr = [];
$('tr').each(function() {
arr.push($(this).children('td').map(function() {
return $(this).html();
}));
}).get();
console.log(arr);
This uses the standard .push() since I don't think that using .map() inside .map() would work. I think when you pass the inner array into the jQuery object, it just adds it to the main array (or something).
The html() function, and similar functions like text() and width() return a scalar value for the first matched element.
If you want an array with the HTML contents of every matched element, you should call map(), like this:
var arr = $(value).children('td').map(function() { return $(this).html(); }).get();
alert(arr[0]); //Alerts HTML of first <td> element
The .html() function:
Description: Get the HTML contents of
the first element in the set of
matched elements.
This is true of many jQuery functions that are retrieving values. So what's happening is that your filter function is returning a set of jQuery elements, but your .html() function is causing arr to just be assigned the html from the first element in the set.