📜 ⬆️ ⬇️

5 useful jQuery API methods you might not know about

In this article, I will talk about five jQuery methods that I found useful for myself and which, according to my observations, very few people know.

I’ve been working with jQuery for about two years, but until recently I didn’t use these methods, since you can do without them. But it can be much easier with them.


jQuery.grep ()

jQuery.grep(array, function(elementOfArray, indexInArray) [, invert]) - as you might guess from the name, the method filters the array elements relying on the result of the function (the original array does not change). JQuery also has a similar .filter() method which serves to filter the set of items found.
')
Example

You need to select from the array only multiples of 3:
 var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; console.log($.grep(arr, function(el){ return el % 3 === 0 })); // [3, 6, 9, 12, 15] 


.map ()

.map( callback(index, domElement) ) - the method is useful in that it allows you to do transformations over selected elements or an array without writing loops (for arrays, use jQuery.map() ).
If the function returns null or undefined, the element will be ignored.

Example

We will display the addresses of all the links on the page:
 var links = $('a').map(function(el){ return this.href; }).get().join("\n"); console.log(links); 


jQuery.proxy ()

jQuery.proxy( function, context ) - it can be useful if you need to pass a callback, but set its own context for it (the value of the variable this ).

Example

 var myObj = { message: 'hello', alertMessage: function(){ //  this    myObj, //    ,    alert(this.message); return false; } }; $('a').click($.proxy(myObj.alertMessage, myObj)); 


.prop ()

.prop( propertyName, value ) - this method appeared in version 1.6 and I have been using it since about the same time. But I decided to mention here because many mistakenly use the .attr() method to access the properties of elements and modify their values.
The fact is that since version 1.6 .attr() works directly with the attribute of the element and in some cases the result is not exactly expected.
For example, if we want to know the state of the checkbox, then .attr() can .attr() its default value (which can be seen in the HTML source of the page). In this case, we need to use the .prop() method - it will return the current value of the element property.

Example

Invert all checkboxes on the page:
 $('input').prop('checked', function(el, oldVal){ return !oldVal; }); 


.serializeArray ()

.serializeArray() is a very simple way to serialize form data as an array or string (in this case, use .serialize() ). The method returns an array, which then for example can be sent via ajax to the server.

Example

 var arr = $('#myForm').serializeArray(); //  arr    {name: "field-name", value: "field-value"} 

Source: https://habr.com/ru/post/146630/


All Articles