Jquery html element this

this and $(this) in jQuery callbacks

What’s this and $(this) in jQuery callbacks? I’ve used them extensively, but never really paid attention to them until after I wrote the posts on what this is in JavaScript (part1 and part2). Now that I know how this works in JavaScript I got curious on how this is handled in jQuery and how $(this) is bound to the current element in jQuery event handler callbacks. The findings were not surprising, but rather show that jQuery is a well designed library.

Summary

  • this is a reference to the html DOM element that is the source of the event.
  • $(this) is a jQuery wrapper around that element that enables usage of jQuery methods.
  • jQuery calls the callback using apply() to bind this .
  • Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.

Let’s a have a look at how jQuery handles those cases internally.

jQuery $(this)

Calling $(this) ends up in the part of the jQuery constructor that takes care of a supplied DOMElement:

// Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; }

// Handle $(DOMElement) if ( selector.nodeType )

How jQuery Calls the Event Handler

When jQuery calls the event handler callback, it is done by using the apply() function and supplying the matched element as this .

ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args );

ret = ( (jQuery.event.special[ handleObj.origType ] || <>).handle || handleObj.handler ) .apply( matched.elem, args );

(Don’t ask me about the first line. It tries a few different ways of getting hold of the function to call, but I haven’t dug into the details so I have no idea of why).

Handling $($(this))

The last thing I looked at was how jQuery handles the common mistake where $(selector) is called on a variable that is already the result of another call to $(selector) . At the end of jQuery.fn.init function there is a block handling this special case:

if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; }

if ( selector.selector !== undefined )

The jQuery code snippets are taken from jQuery version 1.8.0

You’re currently writing a reply to an existing comment, so the comment form is busy elsewhere. To make a new comment (that isn’t a reply to an existing ocmment), you have to cancel that reply.

I’m Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

Читайте также:  Python язык программирования предназначен для

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Источник

jQuery $(this) Selector — Explained with Examples

jQuery $(this) Selector — Explained with Examples

html-tuts.com

If you are a developer, you might have come across several tutorials or code snippets using the $(this) selector in jQuery. Unfortunately, most of the resources you will find online don’t expound much on the working of the $(this) selector.

This article will give an in-depth explanation about $(this) selector in jQuery using various examples and code snippets that you can run on your PC.

The jQuery $(this) Selector

The $(this) selector in jQuery is used to select the current element that the event is being called on. This selector is often used within event handlers, such as click or hover events, to reference the element that was interacted with.

The $(this) selector is a powerful tool that allows developers to create dynamic and interactive web pages by manipulating the selected element in various ways.

It’s also useful when you have multiple elements with the same “class” or “id” and you want to target one specific element.

With the $(this) selector, you can easily access and modify the properties of the selected element, such as its CSS styles, HTML content, and attributes.

Are you just getting started with jQuery? If yes, please feel free to check our post on The 2 Best Ways to Add jQuery to HTML.

Understanding the jQuery $(this) Selector

Before getting started with complex examples, let us use the popular console.log() method to see how jQuery accesses HTML elements.

We have a simple HTML page with one paragraph tag which has the class name of testClass as shown below.

You will also notice that we are calling the index.js file at the bottom which contains our jQuery code.

Inside our jQuery code we will access the paragraph using the testClass and console.log() the value of $(this) as shown in the code below.

When you open the browser console, you will see an output similar to the image below.

This jQuery code above binds a click event to the element with the class testClass.

When this element is clicked (our paragraph), the code inside the event handler function is executed.

The code inside the function uses console.log($(this)) to log the selected element (the HTML paragraph) to the browser’s console which is shown in the image above.

In simple terms, this code will select all elements with the class testClass and when any of these elements are clicked, it will log the element to the browser’s console.

Example 1: Using jQuery $(this) Selector with .click Function

As you learned in the previous section, the jQuery $(this) selector is used to select the current HTML element that the user is interacting with.

The .click() function is used to attach a click event to the selected element.

In the HTML file create a simple button that you will manipulate using jQuery when clicked.

Inside the jQuery code, we will use the $(this) selector with the .click() function to toggle the background color of the button when it is clicked. See the code below.

Читайте также:  What is secretkeyfactory in java

In this example, the $(“button”) selector selects all button elements on the page.

The .click() function is then used to attach a click event to the button, and the anonymous function inside of the click() function is executed when a button is clicked.

The $(this) selector is used to select the button that was just clicked, and the .toggleClass(“active”) function is used to toggle the “active” class on and off for the selected button.

You can add CSS styling to change the color:

In this example, when a button is clicked, its background color will toggle between the default color and red. See the image below.

Example 2: Using jQuery $(this) Selector with .each Function

The .each() method in jQuery is used to iterate over a set of elements in a selection.

It allows you to execute a function for each element in the set, and the function is passed the current element in the set as an argument.

The .each() method is typically used to perform some operation on each element in a selection, such as modifying the element’s properties or attributes, or binding an event handler to the element.

Example 3: Using jQuery $(this) Selector with .hover Function

The .hover() function is used to attach two event handlers to the selected elements: one for mouseenter and one for mouseleave.

In your HTML code, create a button and give it a class name of .my-button as shown in the code snippet below.

Below is the jQuery code that uses $(this) with the .hover() function.

The jQuery code above is using the $(“.my-button”) selector to select all elements with the class “my-button”. Then it is attaching the .hover() function to those elements.

The .hover() function takes two arguments: the first is a function that will be executed when the mouse enters the element, and the second is a function that will be executed when the mouse leaves the element.

In the first function, it is using the $(this) selector to select the current element that the mouse is hovering over, and then it is using the .css() function to change the background color of the element to “red”.

In the second function, it is again using the $(this) selector to select the current element that the mouse is leaving, and then it is using the .css() function to change the background color of the element back to “white”.

In summary, this script will change the background color of all elements with the class “my-button” to red when the mouse hovers over them, and change the background color back to white when the mouse leaves the element.

How can I use the $(this) selector to target a specific child element of the current element?

To target a specific child element of the current element, you can use the $(this) selector in combination with the find() method. The find() method allows you to search for elements within the current element.

For example, if you have a div with the class “myDiv” that contains a span with the class “mySpan”, and you want to change the text color of the span when the div is clicked, you could use the following code:

Читайте также:  No scroll window css

Источник

jQuery’s this: demystified

More often that not, in my early dabbling with jQuery and more advanced JavaScript, I found I would constantly get confused over the meaning of «this» in jQuery and my own new libraries.

Hopefully this quick guide can help clarify those confusing moments, because once you’ve got it, it’s simple as pie.

READER DISCOUNT Save $50 on terminal.training

I’ve published 38 videos for new developers, designers, UX, UI, product owners and anyone who needs to conquer the command line today.

$49 — only from this link

What is «this»?

In many object-oriented programming languages, this (or self) is a keyword which can be used in instance methods to refer to the object on which the currently executing method has been invoked.

jQuery’s this

There are really two main contexts of ‘this’ in jQuery. The first refers to a to a DOM element, and the second to a jQuery object.

Example of this as a DOM element

‘this’ is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.

The following code searches for anchor links with the class of ‘newTarget’ and sets the ‘target’ attribute to ‘_new’ (which is a trick to create strict XHTML while still having some links open in a new window).

In this example we are also going to perform a double check to ensure links to the same domain don’t open in a new window using the this object.

Example of this as a jQuery object

‘this’ is a jQuery object when you are inside your own jQuery functions. Note that the result of a selector query (i.e. $(‘a’) ) is a jQuery object, which is an array of the matched DOM elements (imagine jQuery is an array with bells on).

jQuery.fn.newTarget = function() < // 'this' is a jQuery object at this point - with all the jQuery functions return this.each(function() < // return so we don't break the chain // now we are inside of a jQuery function, the DOM element is the context // so 'this' has changed to become a DOM element. if (this.host != window.location.host) < $(this).attr('target', '_new'); >>); >;

Finishing up

This is far from comprehensive, but equally there’s very little to the logic. So long as you remember the context of ‘this’ changes when moving in and out of object methods then you’re on your way.

If you’re still not sure, get your hands on Firebug and add ‘console.log(this)’ within your code to interrogate and understand what ‘this’ is at that point in your code.

If this still doesn’t make sense or I’ve got it terribly wrong — or you’re suddenly enlightened, please do let me know — and I’ll do my best to help.

Published 12-Apr 2007 under #explanation & #guide & #javascript & #jquery & #this & #code. Edit this post

Источник

Оцените статью