Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select current element in jQuery

Tags:

jquery

I have HTML code like this :

<div>        <a>Link A1</a>        <a>Link A2</a>        <a>Link A3</a> </div>  <div>        <a>Link B1</a>        <a>Link B2</a>        <a>Link B3</a> </div> 

When user clicks a link from above HTML, I want to get the jQuery object of the corresponding <a> element, and then manipulate its sibling. I can't think of any way other than creating an ID for each <a> element, and passing that ID to an onclick event handler. I really don't want to use IDs.

Any suggestions?

like image 258
Salamander2007 Avatar asked Dec 12 '08 02:12

Salamander2007


People also ask

Which is the correct jQuery selector to select current HTML element?

The #id Selector The jQuery #id selector selects an HTML element based on the element id attribute. Following is a simple syntax of a #id selector: $(document).

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.

How can get li id value in jQuery?

ready(function() { $('#list li'). click(function() { alert($(this). attr("id")); alert($(this). text()); }); });

Does jQuery use CSS selectors to select elements?

jQuery uses CSS selector to select elements using CSS. Let us see an example to return a style property on the first matched element. The css( name ) method returns a style property on the first matched element. name − The name of the property to access.


2 Answers

Fortunately, jQuery selectors allow you much more freedom:

$("div a").click( function(event) {    var clicked = $(this); // jQuery wrapper for clicked element    // ... click-specific code goes here ... }); 

...will attach the specified callback to each <a> contained in a <div>.

like image 180
Shog9 Avatar answered Oct 13 '22 17:10

Shog9


When the jQuery click event calls your event handler, it sets "this" to the object that was clicked on. To turn it into a jQuery object, just pass it to the "$" function: $(this). So, to get, for example, the next sibling element, you would do this inside the click handler:

var nextSibling = $(this).next(); 

Edit: After reading Kevin's comment, I realized I might be mistaken about what you want. If you want to do what he asked, i.e. select the corresponding link in the other div, you could use $(this).index() to get the clicked link's position. Then you would select the link in the other div by its position, for example with the "eq" method.

var $clicked = $(this); var linkIndex = $clicked.index(); $clicked.parent().next().children().eq(linkIndex); 

If you want to be able to go both ways, you will need some way of determining which div you are in so you know if you need "next()" or "prev()" after "parent()"

like image 31
Matthew Crumley Avatar answered Oct 13 '22 17:10

Matthew Crumley