Vijikumar M
Vijikumar M

Reputation: 3764

How to extract a attribute in Jquery?

I want to extract a particular attribute from a tag.

I am getting

 var item=<a href="/tasks/new?count=2&amp;task_id=157" class="right">tttttttttttt_wo /   nnnnnnnnnn_wo</a>

From this i want to extract only task_id. How to do that?

Upvotes: 1

Views: 163

Answers (4)

Pramod S. Nikam
Pramod S. Nikam

Reputation: 4539

You can get that in 2 stages :

  1. get attribute using jquery.attr
  2. match that task_id regex using jquery match function

Code:

var strings =  $('a.right').attr("href").match(/task_id=[0-9]+/);    
alert(strings[0]);

jsfiddle for your reference.

Upvotes: 2

Rakesh Shetty
Rakesh Shetty

Reputation: 4568

You want to say like this ? - Fiddle Demo 1 OR Fiddle Demo 2

Fiddle Demo 1 Code :

HTML :

<a href="/tasks/new?count=2&amp;task_id=157" task_id = "157" class="right">tttttttttttt_wo /   nnnnnnnnnn_wo</a>

jQuery :

$(document).ready(function(){

    $('.right').click(function(){

           var task_id = $(this).attr('task_id');
           alert(task_id);


    });

});

Fiddle Demo 2 Code :

HTML :

<a href="/tasks/new?count=2&amp;task_id=157" class="right">tttttttttttt_wo /   nnnnnnnnnn_wo</a>

jQuery :

$(document).ready(function(){

    $('.right').click(function(){

          alert($('a').attr('href').split("&").pop());    

    });

});

Upvotes: 2

Matilda Yi Pan
Matilda Yi Pan

Reputation: 658

First of all, task_id is not an attribute, but href is. so you can get the value of href by

$('a.right').attr("href")

Upvotes: 0

Janani M
Janani M

Reputation: 423

HTML:
<a href="/tasks/new?count=2&task_id=157" class="right">tttttttttttt_wo /   nnnnnnnnnn_wo</a>

Jquery:
alert($('a').attr('href').split("&").pop());

Upvotes: 1

Related Questions