tags:

views:

338

answers:

3

If I had something like:

<a>Content 1</a>
<a>Content 2</a>
<a>Content 3</a>

And I wanted to get the what's in between the anchor tags (the words being clicked), how would I go about that? The links are shown dynamically, so I can't add an id attribute to them. (I think I can't, at least.)

+2  A: 

This should work to select all:

$('a').each(function() { $(this).text(); /* do something with it */ });

if you want to get the click event on anchor tags, but only those without an id or class, try this:

$('a').not('a[id]').not('a[class]').click(function() { $(this).text(); ... });

and if you only want your action to be performed once:

$('a').not('a[id]').not('a[class]').one("click", function() { $(this).text(); ... });
Jim Schubert
I only want the content of the one clicked, though. Is that possible, while keeping the anchor tags like they are?
Andrew
change .each to .click, somehow I missed the "clicked" part
Jim Schubert
That worked wonderfully. Thanks. :)
Andrew
Thanks. also added a couple more options in case you have other links on the page that you want to exclude.
Jim Schubert
+1  A: 

You can use any CSS selector that matches these tags to get a jQuery object for them.

You can then use text() to get the contents of a tag in plain text, or html() to get the direct html code, including any nested tags.

Example:

$('a').each(function() {
     alert($(this).text());
});
Tobias Cohen
+1  A: 

If the links are actually built dynamically once the page is already served to the client then you will want to wrap your <a> tags with an identifying element and then add an event listener to the wrapping element.

If you want this behavior for all the links on the page, then just use:

$('a').click(
   function() { 
      var link_text = $(this).text();
      //Do something with link_text 
   });
Sean Vieira