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?
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).
$() = 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.
ready(function() { $('#list li'). click(function() { alert($(this). attr("id")); alert($(this). text()); }); });
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.
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>
.
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()"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With