how to use $.makeArray() with jQuery - javascript

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.

Related

How to get value of multiple files in array without any loop statement

Is it possible to get value of all elements return by find or children method without loop?
There is multiple li that contai hidden field and we want to get all these hidden field val.
i.e. var cats = $(this).next('ul').find('.hdn_id').val();
But its return only single value.
You need to iterate the elements, For simplicity .map() can be used.
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
var cats = $(this).next('ul').find('.hdn_id').map(function () {
return $(this).val();
}).get();
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.
.contents()
.filter(function(){
return this.nodeType !== 1;
})

jquery exclude array elements

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

jQuery .data('key') for all elements

When using .data('keyname') on a jQuery set, I only seem to get the first value. I would like it to return an array of values from each element.
Is there a jQuery shortcut for pulling all values that does not involve iterating the set yourself?
Use .map:
var dataValues = $(".yourElementSelector").map(function() {
return $(this).data("keyname");
}).get();
This is about as short as it gets... dataValues will now be a nice array of your data('keyname') values.

Quick Javascript thought about document.getElementByClassName for fixing error

Quick JS question :
if you do something like :
var text = document.getElementByClassName("grid3").innerText;
what is the best way if you have multiple elements with that class?
what is the best way if you have multiple elements with that class?
It depends which element you want to reference... your example will always fail because that method returns a NodeList regardless of the number of elements. Note that it's getElementsByClassName (plural "elements").
If you want to get the first:
var text = document.getElementsByClassName("grid3")[0].innerText;
If you want to get them all (in an array):
var allText = [].map.call(document.getElementsByClassName("grid3"), function (elem) {
return elem.innerText;
});
Its document.getElementsByClassName("grid3") with s...you will always get back an array of Objects. Therefore innerText will not work there.
You could get the innerText of single elements in this array like this:
var el = document.getElementsByClassName("grid3");
var text = el[0].innerText;
Or if you have just one element with that class, give it a id and use
var el = document.getElementById("yourelementsid");
Here is a fiddle that shows how it works and not works:
Fiddle
There is no method document.getElementByClassName, you lost "s".
document.getElementsByClassName always returns an array (or array-like object), so you have to loop througt this array to find what you want.
document.getElementByClassName() return a list of elements so you can use it as array.
var textArr = document.getElementByClassName("grid3");
for(var i = 0; i< textArr.length; i++){
// here is your text
var text = textArr[i].innerText;
}

Select all HTML ID's as a jQuery Object

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
});

Categories