DEV Community

Uriel Bitton
Uriel Bitton

Posted on

5 Useful Jquery functions every web programmer should know + Advanced DOM Traversal techniques

Jquery & The DOM

Most web programmers know and love jquery for its simplification from javascript and efficiency. Manipulating the DOM with jquery can be highly powerful in terms of web programming and design. For a beginner jquery can seem intimidating so here are the 5 perhaps most used jquery functions and tools ever web designer should have in their toolbox.

1. find

The find method is perhaps the most useful for DOM traversal or targeting a specific element buried deep down in the DOM tree. For example say we have the following code:

<div class="section">
   <div class="container">
      <div class="box">
         <h2 class="title">Title</h2>
         <p>Hello</p>  
      </div>
   </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Say we would like to access the h2 element we would write in jquery:

$('.section').find('h2');
Enter fullscreen mode Exit fullscreen mode

Now we can manipulate that element and change its text and color like so:

$('.section').find('h2').css('color','red');
$('.section').find('h2').html('Subtitle');
Enter fullscreen mode Exit fullscreen mode

We can also use find by class or id instead of tag.

$('.section').find('.title');
Enter fullscreen mode Exit fullscreen mode

2. eq

If you're familiar with the css pseudo selector nth-child() or nth-of-type() then think of the eq() method as the jquery equivalent. Say we have a collection of elements and we wish to access a certain child or maybe all of them incrementally:

<ul class="myList">
   <li>Tony</li>
   <li>Bruce</li>
   <li>Steve</li>
   <li>Natasha</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

In jquery, we can access the 2nd element as so:

$('.myList li').eq(1).html('Banner');
Enter fullscreen mode Exit fullscreen mode

*Note: unlike nth-child() selector, the first element in eq() is 0 and not 1.

We can also really amp up the power and do some cool stuff if we want. Let's replace the text contents of every list item using the eq method.

var array = ['Stark','Banner','Rodgers','Romanoff']; //create an array with new text contents

for(i=0;i<=array.length;i++) {
   $('.myList li').eq(i).html(array[i]); //loop over the array and overwrite the text contents with the contents in our array
}
Enter fullscreen mode Exit fullscreen mode

3. split

This one is very useful for generating array elements quickly.
Say we have a p tag that contains text which we wish to split up and manipulate like so:

<div class="stones">
<p>power,time,soul,reality,space,mind</p>
</div>
Enter fullscreen mode Exit fullscreen mode

We can manipulate these text contents in jquery:

var stones = $('.stones p').html(); //assign the contents of our p tag to a variable called stones
var newarray = stones.split(','); //split the contents by commas, this creates an array: ['power', 'time', 'soul','reality','space','mind']
Enter fullscreen mode Exit fullscreen mode

We can now manipulate this array in any way we want, maybe add each element to a list:

$('.stones').html('<p>Here are the six infinity stones:</p> <ul><li>'+newarray[0]+'</li><li>'+newarray[1]+'</li><li>'+newarray[2]+'</li><li>'+newarray[3]+'</li><li>'+newarray[4]+'</li><li>'+newarray[5]+'</li></ul>');
Enter fullscreen mode Exit fullscreen mode

Neat.

4. addClass/removeClass

The add/remove class method is self-explanatory. If we would like to add a class to an element based on some event (or statically) and/or remove another class we can do so like this:

<h4 class="correct">Good answer!</h4>
Enter fullscreen mode Exit fullscreen mode

In our css we can style this element

.correct {color:green}
Enter fullscreen mode Exit fullscreen mode

We will also add a style for a class "incorrect"

.incorrect {color:red}
Enter fullscreen mode Exit fullscreen mode

In our jquery:

$('.correct').html('Wrong answer.').removeClass('correct').addClass('incorrect');
Enter fullscreen mode Exit fullscreen mode

5. parents/parentsUntil

This one can be extremly useful for handling hover events amongst many other uses. Imagine we have a container element with many children elements inside. Using parents/parentsUntil method, we can access the child's parents at whatever level we desire. You can think of it as the reverse of the find method.

<div class="container">
   <div class="section">
      <div class="inner">
         <h1 class="title">Hello</h1>
      </div>
   </div>
</div>
Enter fullscreen mode Exit fullscreen mode

With jquery we can access a parent of our h1 tag like so:

$('.title').parents('.container').css('border','2px solid black');
Enter fullscreen mode Exit fullscreen mode

We can also use parentsUntil

$('.title').parentsUntil('.container').css('border','2px solid black');
Enter fullscreen mode Exit fullscreen mode

Notice how this adds another border. The difference between parentsUntil() and parents() is parents() will get us ALL of the parents of that element (optionaly filtered by a selector in the parameter) whereas parentsUntil() will get us all the parents of that element except the element specified in its parameter.

We can also use parents() in combination with find for a more powerful technique of traversing the DOM without limits.

<div class="container">
   <div class="cont2">
      <h4>Another title</h4>
      <div class="cont3">
         <p class="text">This is some text</p>
      </div>
   </div>
   <div class="section">
      <div class="inner">
         <h1>Hello</h1>
      </div>
      <h1>Hi there</h1>
      ...//some other divs with h1 tags...
   </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Say we would like to dynamically manipulate out h1 tag with contents "Hello" from our p tag (class="text") point of view, e.g. clicking the p tag should trigger some event to the h1 tag. This seems quite challenging, especially if we have multiple divs with h1 tags that also have the same class "section" and "container" and also since our h1 tag has no class or id. But with the use of parents() and find() we can achieve this quite easily.

//after a click on our p tag with class "text"...
$('.text').parents('.container').find('.section').find('.inner h1'); //from our "text" element we go all the way up its parents and stop at "container" then from there we run a search for a "section" element and then again for a "inner" and then our h1
//we can then make some changes to it
$('.text').parents('.container').find('.section').find('.inner h1').html('Hello World');
Enter fullscreen mode Exit fullscreen mode

Bonus: append/prepend Method

The append (and prepend) method is perhaps the most used method in web programming. Append helps us add elements and text to the DOM dynamically, wherever we want to. Unlike the html() method which writes elements and text to the DOM, by effectively overwriting its contents with the new content, append/prepend adds to an element without overwriting what was previously inside it.

A simple example can help us demonstrate its use:

<p>How are you today</p> 
Enter fullscreen mode Exit fullscreen mode

To add text after hello we can write in our jquery:

$('p').append(', John?');
Enter fullscreen mode Exit fullscreen mode

This will yield "How are you today, John?"

We can also use prepend like so:

$('p').prepend('Welcome John, ');
Enter fullscreen mode Exit fullscreen mode

This will yield "Welcome John, How are you today"

or both together:

$('p').append(', John?');
$('p').prepend('Welcome John, ');
Enter fullscreen mode Exit fullscreen mode

This will yield "Welcome John, How are you today, John?"

The nice thing about this is that the order in which we write these lines of code don't matter, any order will yield the same result.

We can also add html elements with append/prepend and not just text:

$('p').append($('<button>Hello</button>')); //this will add a button after the text 
Enter fullscreen mode Exit fullscreen mode

Conclusion

Jquery is a powerful and efficient library (programming langauge) and these common functions helps us traverse and manipulate the DOM without limitation.

Let me know what you think of these jquery functions and if you use them as often as i think we do, or if you think there are functions more useful than the ones i mention. I would love to hear from you.

As always, thanks for reading and I'll be seeing you at my next post!

Uriel Bitton
Website: www.scorpionedge.com
Portfolio: urielbitton.design
Email: urielas@hotmail.com

Top comments (0)