0

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

3
  • 1
    try $(this).find("a").attr("tool") Commented Aug 25, 2016 at 9:50
  • it works! Many thanks! What i did wrong? Commented Aug 25, 2016 at 9:52
  • check answer below if it help you Commented Aug 25, 2016 at 9:53

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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');

1 Comment

This looks better because it keeps the selector instead of finding of every time.
0

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');

Comments

0

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');

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.