TWO USEFUL jQUERY METHODS AND A JS ONE
So, let’s get started!
The ‘.each’ jQuery method is among the most used; it simply iterate over a jQuery object, running a callback function every time it iterates.
However the jQuery documentation recommends to use this method carefully because many jQuery methods already iterate the matched elements: so for example adding a class to an element targeted by ‘.target’ class with jQuery ‘.addClass’ method automatically will iterate all the ‘.target’ elements and apply to all them (we speak about “implicit iteration” in this case).
Here comes the nice of the .each method. It give us a context to which will apply our callback functions and inside of it we can use the keyword ‘this’ to refer to our specific element. We will se in the next Friday post how this detail will be crucial for our purposes.
NOTE that ‘.each()’ method is something different from the ‘$.each()’ one: the latter one, in fact, will iterate both objects and arrays and the callback is passed an index-value (if array) or key-value (if object) pair each time.
In our previous jQuery-focused post we talked about .before that adds some html elements right before, in the Dom tree, the element selected. Here we give a look at a similar method that adds it after (look at the related .prepend for adding before); however, the major difference is that the .append() method adds the html you want as the last child of the element matched by selector, so, definitely, still inside of it.
As you can see the syntax is very simple. The .appendTo() method is exactly the same except that it invert the element order in the syntax.
NOTE that such as for the .before() method it accepts passing multiple arguments as input.
IN THE FRIDAY POST
In the next post, on Friday, we will see how we used these three jQuery methods fo getting the result you can see also above in this post: a blue button appended to our jQuery method titles (.each, .append and .replace) that automatically grab the title and redirect to the correct jQuery documentation page.
See you next post!