Andrew
Andrew

Reputation: 238627

jQuery: How to get the value of an html attribute?

I've got an html anchor element:

<a title="Some stuff here">Link Text</a>

...and I want to get the contents of the title so I can use it for something else:

$('a').click(function() {
    var title = $(this).getTheTitleAttribute();
    alert(title);
});

How can I do this?

Upvotes: 7

Views: 25611

Answers (6)

Prince Patel
Prince Patel

Reputation: 3060

You can create function and pass this function from onclick event

<a onclick="getTitle(this);" title="Some stuff here">Link Text</a>

<script type="text/javascript">

function getTitle(el)
{
     title = $(el).attr('title');
     alert(title);
}

</script>

Upvotes: 0

Archis
Archis

Reputation: 21

Even you can try this, if you want to capture every click on the document and get attribute value:

$(document).click(function(event){
    var value = $(event.target).attr('id');
    alert(value);
});

Upvotes: -1

rahul
rahul

Reputation: 187020

You can simply use this.title inside the function

$('a').click(function() {
    var myTitle = $(this).attr ( "title" ); // from jQuery object
    //var myTitle = this.title; //javascript object
    alert(myTitle);
});

Note

Use another variable name instead of 'alert'. Alert is a javascript function and don't use it as a variable name

Upvotes: 2

Josh Gibson
Josh Gibson

Reputation: 22908

$(this).attr("title")

Upvotes: 1

awgy
awgy

Reputation: 16914

$('a').click(function() {
    var title = $(this).attr('title');
    alert(title);
});

Upvotes: 1

yoda
yoda

Reputation: 10981

$('a').click(function() {
    var title = $(this).attr('title');
    alert(title);
});

Upvotes: 8

Related Questions