Reputation: 987
My markup looks like this:
<ul>
<li><span class="mystyle">List Item 1</span></li>
<li><span class="mystyle">List Item 2</span></li>
<li><span class="mystyle">List Item 3</span></li>
</ul>
I want it to look like this:
<ul>
<li><span class="mystyle"><a href="#">List Item 1</a></span></li>
<li><span class="mystyle"><a href="#">List Item 2</a></span></li>
<li><span class="mystyle"><a href="#">List Item 3</a></span></li>
</ul>
Using jQuery, how can I add an HTML tag to all elements with the "mystyle" class?
Upvotes: 0
Views: 4156
Reputation: 25882
Use this
$('.mystyle').each(function(){
$(this).html('<a href="#">'+$(this).text()+'</a>');
});
.html
overwrites the old html of an element with the new content, given as parameter.
Upvotes: 2
Reputation: 24638
Use either jQuery.wrap() --- DEMO
$('.mystyle').contents().wrap( $('<a/>',{href:'#'}) );
Or jQuery.wrapInner() --- DEMO
$('.mystyle').wrapInner( $('<a/>',{href:'#'}) );
.wrap()
- Wraps an HTML structure around each element in the set of matched elements.
.wrapInner()
- Wraps an HTML structure around the content of each element in the set of matched elements.
Upvotes: 2
Reputation: 9637
try
$(".mystyle").each(function () {
$(this).html('<a href="#">' + $(this).text() + '</a>');
});
Upvotes: 2
Reputation: 20313
Use .wrapInner()
. Try this:
$('.mystyle').each(function(){
$(this).wrapInner('<a href="#"></a>');
});
Upvotes: 4
Reputation: 82231
First of all you have incorrect markup, you need to close span tags used. then you can use the JS:
$('.mystyle').each(function(){
$(this).html('<a href="#">List Item '+$(this).html()+'</a>');
});
Upvotes: 2