- Inserting Elements
- Creating a Lightbox Effect
- More Fun with DOM Manipulators
- Getting and Setting Measurements
- Cloning
- Changing an Input Element
- Rewind and Review
More Fun with DOM Manipulators
Let’s look at more ways to use some of the other DOM manipulators.
To use before() to rearrange order
- Open a new copy of the HTML5 boilerplate in your text editor and add the following markup (Script 4.2.html):
<div id="content> <div class="article"> <h3>Article 1</h3> <p>Lorem ipsum...</p> <a href="" class="mover"> move to top</a></div> <div class="article"> <h3>Article 2</h3> <p>Lorem ipsum... </p> <a href="" class="mover"> move to top</a></div> <div class="article"> <h3>Article 3</h3> <p>Lorem ipsum...</p> <a href="" class="mover"> move to top</a></div> <div class="article"> <h3>Article 4</h3> <p>Lorem ipsum...</p> <a href="" class="mover"> move to top</a></div> <div class="article"> <h3>Article 5</h3> <p>Lorem ipsum...</p> <a href="" class="mover"> move to top</a></div> </div>
- Save the file as article.html and upload it to your web server. Load the page into your browser .
- Modify jquery.custom.js with the following code to move an article to the top of the list of articles:
$('.mover').click(function(e) { e.preventDefault(); $('#content div:first') .before($(this).parent('div')); });
- Save the jQuery file and upload it to your web server.
- Reload article.html in your web browser and click on any of the “move to top” links. The article moves to the top of the list .
You can rearrange the list to bring an article to the top.
Let’s look at what’s in play here. Using before() makes things read backward so the selector selects the first div, using a jQuery selector extension (more about those in Chapter 5, “Harnessing Advanced Selectors”), :first. The first div in the group is the div you’ll insert your chosen div before. Whew. Then you invoke the before() method to carry your chosen div to the first spot in the group .
To get the chosen div, you get the parent div of the clicked link. The parent() method is a DOM traversal method you’ll see again in Chapter 6, “Traversing the DOM Tree.”
The before() method has a counterpart that performs the same job exactly, the insertBefore() method. The insertBefore() method has one huge advantage: It’s much easier to read:
$(this).parent('div') .insertBefore($('#content div:first'));
This line of code says to take the clicked element’s parent div and insert it before the first div in the selected group of divs. Which one should you use? As mentioned earlier, it’s a matter of personal preference.