Haritz
Haritz

Reputation: 1752

store HTML tag attribute value in a variable using Jquery

I am developing an application using JQuery. This is a fragment of the HTML code I am using:

<MarkNag class="altcheckboxoff" id="markable_38" Azpimark_id="100038">helburua </MarkNag>    
<MarkNag class="altcheckboxoff" id="markable_2"  Azpimark_id="100002">Oriolek </MarkNag>
<MarkNag class="altcheckboxoff" id="markable_39" Azpimark_id="100039">gas liberalizazioa </MarkNag>

I have the next JQuery script in the HTML page:

<script type='text/javascript'>
   $("MarkNag").click(function (){
      $(this).toggleClass("highlight");
   });
</script>

I would like to know how could I store "markable_39" in a variable if this MarkNag tag was clicked. I guess I should use .data(). But I dont really know how. Any ideas? Thanks

Upvotes: 1

Views: 5065

Answers (5)

Gaurav
Gaurav

Reputation: 8487

here u will get object from where the event occurs

var eventobject = arguments.callee.caller.arguments[0];

here u can access any attribute of currentTarget (in this case id)

var id = $(eventobject.currentTarget).attr("id");

Upvotes: 0

vol7ron
vol7ron

Reputation: 42099

$("MarkNag").click(function (){
   $(this).toggleClass("highlight");

   alert(this.id);               // Method 1: this.id
   alert($(this).attr('id'));    // Method 2: $(this).attr('id')
});

Upvotes: 0

Robbie Ferrero
Robbie Ferrero

Reputation: 173

Also, you can just use this.id, like:

var id = this.id;

Upvotes: 2

Adil
Adil

Reputation: 148110

Do it like this

$("MarkNag").click(function () 
 {
       $(this).toggleClass("highlight");

       var IdOfTag = this.id;
       //or
       IdOfTag = $(this).attr('id');  

 });

Upvotes: 2

Ashley Strout
Ashley Strout

Reputation: 6258

Actually, the correct code would be $(this).attr("id").

Upvotes: 1

Related Questions