Joe
Joe

Reputation: 1635

Get the text of the next attribute

I am looking at getting text of the next attribute (class) of what I currently clicked on. Something like this...

$(this).next().attr('class').text();

Thanks

Edit

Here is my HTML

<span class="Directory"></span>
<span class="Category">My Account</span>

I want to get the text of class 'Category' when I click on class 'Directory'

Upvotes: 0

Views: 711

Answers (7)

arunes
arunes

Reputation: 3524

Get to next span has class named Category

http://jsfiddle.net/sz9A7/

$(function() {
    $("span.Directory").click(getText);
});

function getText() {
    alert($(this).next('span.Category').text());
}

Upvotes: 0

TimCodes.NET
TimCodes.NET

Reputation: 4699

Handle click event of first element, get the next sibling, then get the text.

$('.Directory').click(function(){
    alert($(this).next().text());
});

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69905

Use this, it will get the text of the next span element with class Category.

$(this).next().text();

$(this).next().attr('class') will give you the class name of the next element.

Upvotes: 0

nightf0x
nightf0x

Reputation: 2039

Use

$(this).next().attr('class')

if you want the value of class attribute for the next sibling.

Use

$(this).next().text()

if you want the text inside the next sibling.

Check this jsfiddle for what i tried

Check this jsfiddle for your html

Upvotes: 0

Alex
Alex

Reputation: 6406

http://jsfiddle.net/muA6R/

$('#button').click(function(e){
    alert($(this).next().attr('class'));
});

You don't need .text().

Upvotes: 0

JKirchartz
JKirchartz

Reputation: 18022

you can put the class name in a variable like so:

var class = $(this).next().attr('class');

to get the name of the class, and a hacky way to use that would be :

   $('.'+class).text();

but if you just want the text of the next element use:

   $(this).next().text();

Upvotes: 0

Guffa
Guffa

Reputation: 700302

Just remove .attr('class') from the code:

$(this).next().text()

This gets the text of the next element. For example into a variable:

var nextText = $(this).next().text();

If there may be some other element between the directory element and the category element, you can use a selector to look for the next element with that specific class:

$(this).next('.Category').text()

Upvotes: 1

Related Questions