Get li attribute using javascript or jquery.
Hi,
I want to get url attribute of li when user click on li.
Code:
<ul>
<li url="http://www.google.com" id="1">Google</li>
<li url="http://www.yahoo.com" id="2">Yahoo</li>
<li url="http://www.bing.com" id="3">Bing</li>
<li url="http://www.facebook.com" id="4">Facebook</li>
<li url="http://www.amazon.com" id="5">Amazon</li>
</ul>
I found following but no idea how it will work
Code:
$('li').click(function() {
alert($(this).data('url'));
});
Any idea how to get li url value when click using javascript or jquery?
- Thanks
Zohaib.
Change
$(this).data('url')
to
$(this).attr('url')
(Note however that li elements don't have an 'url' property, so your code is not completely valid. But it will probably work anyway in browsers because they are not that strict.)
Naturally <li> don't have url property but with the new HTML5, you can create one like so:
<li data-url="http://www.amazon.com" id="one"> item1 </li>
And then you can call it with:
$('li#one').click(function() {
alert($(this).attr('data-url'));
});
You cannot do this:
$('li').click(function() {
alert($(this).attr('data-url'));
});
Reason is because you have many list, so you need to loop troop them like so:
$('li').each(function() {
$(this).click(function() {
alert($(this).attr('data-url'));
});
});
Reference: http://api.jquery.com/each/
Naturally <li> don't have url property but with the new HTML5, you can create one like so:
<li data-url="http://www.amazon.com" id="one"> item1 </li>
And then you can call it with:
Code:
$('li#one').click(function() {
alert($(this).attr('data-url'));
});
You cannot do this:
Code:
$('li').click(function() {
alert($(this).attr('data-url'));
});
Reason is because you have many list, so you need to loop troop them like so:
Code:
$('li').each(function() {
$(this).click(function() {
alert($(this).attr('data-url'));
});
});
Reference: http://api.jquery.com/each/
Regards,
Zitemedia
Originally Posted by
zitemediauser
You cannot do this:
Code:
$('li').click(function() {
alert($(this).attr('data-url'));
});
That's not right. $('li').click(function) will add one event listener to each one of the li elements, so this code works perfectly. It even works better than your other method that uses .each() because there you create a new event handler function for every single element, which would be completely unnecessary!
'this' in the above code always refers to the clicked li element. The other elements are not affected at all.
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Bookmarks