Can I use jQuery to change the content of links on a page?
My HTML looks like this:
<div id="control"> <a href="/xx/x">y</a> <ul> <li><a href="/C003Q/x" class="dw">x</a></li> <li><a href="/C003R/xx" class="dw">xx</a></li> <li><a href="/C003S/xxx" class="dw">xxx</a></li> </ul> </div> Is there a way to use jQuery that I can easily change this HTML to look like the HTML below, where each link has text that is enclosed in a <span> , and where each href changes to data-href ?
<div id="control"> <a data-href="/xx/x" ><span>y</span></a> <ul> <li><a data-href="/C003Q/x" class="dw"><span>x</span></a></li> <li><a data-href="/C003R/xx" class="dw"><span>xx</span></a></li> <li><a data-href="/C003S/xxx" class="dw"><span>xxx</span></a></li> </ul> </div> +4
user1464139
source share5 answers
You can use each () to repeat elements of type a that have class dw .
$('#control a.dw').each(function(){ $(this).html("<span>" + $(this).text() + "</span>" ); }); If you want to do the same for elements having href like /x , you need to change the selector.
$('#control a[href*="/x"]').each(function(){ $(this).html("<span>" + $(this).text() + "</span>" ) .attr('data-href', $(this).attr('href')) .removeAttr('href');; }); +2