简体   繁体   中英

unable to get the value of href from a tag using jquery

I am trying fetch the href value in an <a> with a class of "title". The result here should be the path "../../images/packages2/agra1.jpg" but somehow it's not working. Here is my HTML:

  <div id="packgeImages">
        <ul>
<li><a class="title" href="../../images/packages2/agra1.jpg" rel="shadowbox" title=""><img src="../../images/packages2/agra1thumb.jpg" alt="thumb1" /></a></li>
    </ul>
    </div>

and here is my JavaScript:

  var $title = $('.title').attr("href");

Then I am using alert to check the results.. but somehow it seems blank.

Can anybody tell me what I'm doing wrong?

Use first when finding an element based on a class, as there may be more than one element with the same class name.

var $title = $('.title:first').attr("href");

This works: http://jsfiddle.net/Xs9AC/2/

Edit for your comment:

var arr = new Array(); // Create the array

// Loop through each anchor
$(".title").each(function(){
    arr.push($(this).attr("href"));
});

// Loop through the populated array
for (var i = 0; i < arr.length; i++) {
    alert(arr[i]);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM