View Full Version : Problem with jquery class on this()

10-07-2012, 09:32 AM
Hey Guys!
This is my code so far -


<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="content_swapper.js"></script>
<script type="text/javascript">

<div class="swap_me">a</div>
<div class="swap_me">b</div>
<div class="swap_me">c</div>
<div class="swap_me">d</div>


$.fn.fldr_content_swap = function() {
var args = arguments[0] || {};

After all the elements with the class swap_me are hidden, I'd like it to get the third element with the class swap_me (in the javascript file) ONLY using this() (e.g. I don't wan't to have to send swap_me to the function as a parameter).

How do I do this?

10-07-2012, 10:04 AM
$.fn.fldr_content_swap = function() {
var args = arguments[0] || {};
this.hide().eq(args.show).show(); //third el as a jQuery object is revealed


$.fn.fldr_content_swap = function() {
var args = arguments[0] || {};
alert(this.hide().get(args.show).tagName); //third el as a DOM node has it's tagName property alerted.

Both of these assume that there were at least 3 existing elements passed in. In the case of your scenario, something like:

$('.swap_me').fldr_content_swap({show: 2});

and is a little oversimplified. In both versions to avoid potential errors you would want to check whether or not there were a show property passed to it. In the DOM version you would also want to check if the node exists before doing that with it.

Note: I changed $(this) to this because in a jQuery.fn function, this represents the jQuery collection passed to it. That's unlike an event assignment where this represents the DOM node that received the event. It's also unlike jQuery's .each(), where again this represents a DOM node.

In your function using $(this) won't hurt anything. It is redundant though.