Reputation: 71
I have some working JQuery code, but I have been trying to condense the code down to a for each loop. As you see I have a scenario for a 4th LI, but ideally I would like a loop, so it just automatically keeps the LI count. I have tried a couple ways, but with no success so far. Here is my working code:
$(document).ready(function($) {
//adds link around entire content inside of li
//li #1
var a = $('h2 a', '.slides li:first-child').clone();
a.removeAttr('title').html('');
$('.slides li:first-child').wrapInner(a);
//li #2
var b = $('h2 a', '.slides li:nth-child(2)').clone();
b.removeAttr('title').html('');
$('.slides li:nth-child(2)').wrapInner(b);
//li #3
var c = $('h2 a', '.slides li:nth-child(3)').clone();
c.removeAttr('title').html('');
$('.slides li:nth-child(3)').wrapInner(c);
//li #4 (if exists)
var d = $('h2 a', '.slides li:nth-child(4)').clone();
d.removeAttr('title').html('');
$('.slides li:nth-child(4)').wrapInner(d);
});
I also have a basic JSFiddle set-up where you can work with the existing code, etc @ http://jsfiddle.net/qgBHT/
Any help is appreciated, thanks.
Upvotes: 0
Views: 126
Reputation: 82287
You should probably go from the parent in, instead of the child out. As such, it would work to select the h2 element, and then basically wrap that h2 element with the link, and give that element the link's text. This also benefits from not accidentally altering any events which may have been attached to existing elements.
$('.slides li h2').each(function(){
var a = $('a',this).detach();
$(this).html(a.html()).wrap(a.html(""));
});
Upvotes: 0
Reputation: 5962
This should do the same I believe:
$('.slides li h2 a').each(function(){
var a = $(this).clone();
a.removeAttr('title').html('');
$(this).closest('li').wrapInner(a);
});
Upvotes: 2