Blainer Blainer - 9 months ago 26
Javascript Question

grabbing href tag on click

I am trying to grab the href tag on the element clicked in the "navigation" div
The current code returns "#BiblesandCommentaries" every time no matter what element I click in the navigation div.


<div class="navigation">
<li><a href="#BiblesandCommentaries">الانجيل-تعليقات</a> </li>
<li><a href="#EnquirersLibrary">الاستفسارات</a> </li>
<li><a href="#NewBelievers">مؤمنون جدد</a> </li>
<li><a href="#ChristianLiving">حياة المسيحى</a> </li>
<li><a href="#FamilyLibrary">مكتبة الأسرة</a> </li>
<li><a href="#YoungAdultLibrary">مكتبة الشباب</a> </li>
<li><a href="#WorshipLibrary">مزامير وتراتيل</a> </li>
<li><a href="#BibleTeachings">التدريس</a> </li>
<li><a href="#Leadership">القيادة</a> </li>
<li><a href="#SchoolofChrist">مدرسة الإنجيل</a> </li>
<li><a href="#Dota">شاگرد سازی بصورت شنیدن</a></li>
<li><a href="#MinorityLanguages">فهم المسيح</a> </li>


$('.navigation').click(function() {
test = $(this).find('a').attr('href');
alert (test);


using .find().attr() like that will always get the first one, you need to change the selector for your click function to target the a like this:

$('.navigation a').click(function(e) {
    e.preventDefault(); //use this if you don't want to reload the page
    var test = $(this).attr('href');
    alert (test);

also you should declare your variables.

EDIT ok commenters, I was just fixing his code, but here ya go:

$('.navigation a').on("click",function(){

EDIT haha commenters, let's get pedantic:

$("div.navigation").on("click", "a", function(e) {
    alert ($(this).attr('href'));

without preventing the default operation of the a tag, you'll be reloading the page

EDIT: Want to take it a step further? Forget jQuery. Here's some vanilla JS

document.querySelector("div.navigation").onclick = function(e){