cat
cat

Reputation: 1

Using jQuery, how do you get the text from an anchor link after clicking the following anchor link?

Using jquery I am trying to grab the .text() from an anchor link after clicking a link immediately following the first anchor link. There is no class on either of the two links however there is one for the ordered list. The structure is:

<ol id="articles"> <li>Author name <a href="">Title of article</a> | <a href="" id="button1">link B</a></li> <li>Second author name <a href="">Second title of article</a> | <a href="">link C</a></li> </ol>

Result would be: Clicking on "link B" the alert would say, "Title of article" Clicking on "link C" the alert would say, "Second title of article"

What I have so far is:

$(document).ready(function(){ $("#articles a").click(function(){ var text = $(this).text(); alert(text); }); });

But this just gives me the text for the linked clicked. I need the text of the link prior to the clicked link. Any suggestions to get me on the right path? Thank you.

Upvotes: 0

Views: 67

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115212

You can select the last a all li using #articles li a:last-child and select previous a using prev(). Browse through jQuery's methods for traversing the DOM to see what operations are made available for you to use.

$(document).ready(function() {
  $("#articles li a:last-child").click(function(e) {
    e.preventDefault();
    var text = $(this).prev('a').text();
    alert(text);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="articles">
  <li>Author name <a href="">Title of article</a> | <a href="" id="button1">link B</a>
  </li>
  <li>Second author name <a href="">Second title of article</a> | <a href="">link C</a>
  </li>
</ol>

Upvotes: 1

Related Questions