Update: Solutions with and without jQuery
This answer got so many downvotes for showing an example with jQuery that I decided to add more examples with vanilla JavaScript so that anyone could choose whether to use jQuery or not.
Generally, you can use .previousSibling
in vanilla JavaScript, see:
and you can use .prev()
in jQuery, see:
But keep in mind that those may not work in more complicated cases when you don't know the exact structure of your entire DOM.
Here are few examples of achieving that goal both using jQuery and with vanilla JavaScript, for simple cases with fixed DOM structure and for more complicated cases using classes.
Without classes
For the most simple DOM structures you might get away with putting event listeners on all links and relying on the implicit knowledge of the DOM, but this may not work for more complex situations - for those see the examples with classes below.
With jQuery:
$('a').click(function () {
alert( $(this).prev().text() );
return false;
});
See DEMO.
Without jQuery:
document.querySelectorAll('a').forEach(link => {
link.addEventListener('click', () => {
alert(link.previousSibling.previousSibling.innerText);
});
});
Note that the previousSibling
has to be used twice, because the empty text node that is between tha span and link would be used otherwise.
See DEMO.
Using classes
If the span
is not immediately preceding your a
element then you may also want to do it a little bit differently, also adding some classes to make sure that your code doesn't break any other links on the page:
With jQuery:
$('a.link').click(function () {
alert( $(this).parent().find('span.text').text() );
return false;
});
See DEMO.
Without jQuery:
document.querySelectorAll('a.link').forEach(link => {
link.addEventListener('click', () => {
alert(link.parentNode.querySelector('span.text').innerText);
});
});
See DEMO.
The above code will bind click handlers to every a
element with class "link" which will alert a text contained by its sibling span
element with a class "text". (Of course the class names should be more descriptive than that.)