Just the weekly tutorials.

Using Main / Utility "each" Method to Loop through Objects (Arrays, JSON, Object Literal)

The $.each utility method can be used to loop through values stored in an object. Using "each" we can walk through each item stored in an object or an array and run additional jQuery or JavaScript statements to achieve a certain result.

Select HREF URL Values from All Links on the Webpage

List all links on the web page and send output to console:

// Select all A tags var links = $("a"); // Loops through each selected element $.each(links, function() { // Use .attr() method to get the URL text from a link var url = $(this).attr("href"); console.log(url); });

If the HTML was this:

<a href = "http://www.google.com/">Google</a> is a search engine, <a href = "http://www.twitter.com/">Twitter</a> is a social network, <a href = "http://www.wikipedia.com/">Wikipedia</a> is an encyclopedia.

Then the console result would be this:

http://www.google.com/
http://www.twitter.com/
http://www.wikipedia.com/

One of the LearnjQuery.org readers has asked me a question.

"Couldn't we (or, do we need to) specify the HREF attribute within the selector itself, in order to avoid matching anchor <A NAME = ""> elements instead of hyperlinks <A HREF>?"

We can, but there are some things to consider.

This question makes sense because it would make the CSS selector more precise and easier to read. However, the answer is no you don't need to add "href" into selector. Because of what the rest of the code within the each loop does. Within the "each" loop we already filter it out using the following statement.

$(this).attr("href");

This is not a requirement. It's just the way it is done in this example.

Notice that just as when "name" attribute is present in an a hyperlink, by definition the "href" attribute is absent. So if we filter a tags with href attribute, we are automatically only focusing on href hyperlinks anyway.

The code automatically filters (checks) the element for presence of the "href" attribute. The example in this tutorial is focused on the "each" method, not the CSS selector. However, if you did need that kind of precision, you could still do it the way that is being suggested. jQuery is flexible and there isn't only one way of doing things. This is also true throughout JavaScript and should be considered a general programming/coding lesson.

Let's consider alternatives:

$("a").attr("href").each(function(){ /* we will not even get here */ });

We cannot use the above code because the "attr" method returns a string (contents of the "href" attribute) and an object of type String does not have a method called "each". The JavaScript statement from the example above will fail with a the following syntax error:

Uncaught TypeError: Object http://www.google.com/ has no method 'each'

The selector-only solution does exist. Using the brackets [] which check for the presence of an attribute in an HTML element (it will even work with properties such as "checked", through it should not be used to match properties, use "prop" method for properties) we can achieve this:

$("a[href]").each(function(index, obj){ console.log(obj); });

Note that the following selector could have been used with the same effect / result:

$("[href']);

Looping Through an Array with "each"

The same method "each" can be used to loop through an object of type Array. Let's take a look how "each" can iterate through each index of an array and display its value:

var arr = [10,25,50,75,100]; $.each(arr, function(index, value) { console.log(index + ' = ' + value); });

The output of this code would be the following:

0 = 10
1 = 25
2 = 50
3 = 75
4 = 100

Iterating Through a JavaScript Object to Get "key=value" Pair

Using "each" to iterate through a JavaScript object literal to retrieve variable key name and its value.

// Create an object using Object Literal notation var obj = { "action": "reading", "words": "letter", "numbers": 175 }; $.each( obj, function( key, value ) { console.log( key + " = " + value ); });

The output:

action = reading
words = letter
numbers = 175

Use "each" method every time you need to loop through an array or an object containing multiple indices.

Loop Through a JSON Object

A JSON object is an Object Literal represented by a string. To turn a JavaScript string which represents an object into an actual object, use "JSON.parse" method.

var str = '{ "a": "1", "b": "2" }'; $.each(JSON.parse(str), function(key, value) { console.log(key + " = " + value); });

Output:

a = 1
b = 2

These are the most common uses of "each" method.

Just the weekly tutorials.