Alex Baldwin
Alex Baldwin

Reputation: 59

Get two attributes using Jquery

i've a problem using Jquery.

This is my html markup:

 <li><a class="" value="short" tool="car" type="monov"> text </a></li>

I have to capture, after selecting an LI, "ttol" and "type" attr.

This is my code:

var selectedTool = $(this).attr('tool');
var selectedType = $(this).attr('type');

But it doesn't work, it arrives undefined...But if i use this:

$(this).html();

i get:

<li><a class="" value="short" tool="car" type="monov"> text </a></li>

How can i get these attributes?

Thanks

Upvotes: 0

Views: 131

Answers (5)

Devendra Soni
Devendra Soni

Reputation: 1934

try below code :

    var $anchor = $(this).find("a");
    var selectedTool = $anchor.attr('tool');
    var selectedType = $anchor.attr('type');

you were trying to access the attributes of li and the attributes 'tool' and 'type' are on anchor so it was coming undefined.

Upvotes: 3

Ganesh Putta
Ganesh Putta

Reputation: 2671

Try this. its working fine, Just click on li item in my fiddle you can get those attr values as alerts

$("li").click(function(e) { 
    
		var selectedTool = $(this).find("a").attr('tool');
		var selectedType = $(this).find("a").attr('type');
		alert(selectedTool);
		alert(selectedType);
  
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
            <li><a href="#" class="active" tool="car" type="monov" >Home</a></li>
           
        </ul>

Upvotes: 0

Sofia Ferreira
Sofia Ferreira

Reputation: 39

You are selecting the <li> when you want to select <a>.

Please try this:

var element = $(this).find("a");

var selectedTool = element.attr('tool');
var selectedType = element.attr('type');

Upvotes: 2

Spandan Thakur
Spandan Thakur

Reputation: 368

You have to first select all a tags in li tags. Then get the attr value.

You can try:

$("li a").attr('tool');
$("li a").attr('type');

Upvotes: 0

Satej S
Satej S

Reputation: 2156

This code isn't going to work properly when you have multiple <a> tags.

Ideally, you'll have to add a unique identifier in the form of an id to each a tag. Alternatively, you could give it a class name , and identify one of the element based on it's index.

 <li><a class="" id="carOne"  value="short" tool="car" type="monov"> text </a></li>

You can then use JQuery to get the attributes like this:

$("#carOne").attr('tool');

Upvotes: 0

Related Questions