'JQuery Get String From <img class="www.example.com">

This should be a tweak for the jQuery based image gallery "Galleria". You can click on a thumbnail div called images and it brings you on the site based on the url in the class of the a tag.

Pseudo Code HTML

<div id="galleria">
    <div class="images"><a class="www.google.com" href="bens_img/1.jpg"><img src="bens_img/thumb1.jpg"></a>
    <div class="images"><a class="www.yahoo.com" href="bens_img/2.jpg"><img src="bens_img/thumb2.jpg"></a>
    <div class="images"><a class="www.tokyo.co.jp" href="bens_img/3.jpg"><img src="bens_img/thumb3.jpg"></a>
</div>

Pseudo JQuery (JavaScript)

Get Value from class of <a>
Onclick ".images".this
href to Value from class of <a>


Solution 1:[1]

If i've understood correctly,

$('galleria.images').click(function(){
   window.location.href = $("a", this).attr('class');
});

//although i wonder why you'd put href's within a class attribute. hmmm..

Do take a look at this SO post on valid characters for CSS classes.

Solution 2:[2]

Unless I'm missing something, is there any reason why the URL is in the class of the anchor? You have the image path in the href (normally reserved for the destination URL), and then you have a nested img tag with the same reference. Wouldn't your code look more like this?

    <div class="images"><a href="www.google.com"><img src="bens_img/thumb1.jpg"></a></div>

Solution 3:[3]

Putting this in the $(document).ready(function() { ... }) should fix it.

$('#galleria div.images a').each(function(){
   $(this).attr("href", "http://" + $(this).attr('class'));
});

You're missing closing </div> tags on each of the <div class="images"> too BTW.

Edit: http://jsfiddle.net/Ku6Pc/ is an example to show it working.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Ryan Eastabrook
Solution 3