how would I add a link to each list item?
basically I have a list and i want to use js or jquery to added in href for my search page.
<aside class="listlinks">
<ul>
<li>CRM</li>
<li>CTI</li>
<li>Call Center</li>
<li>Data warehouse</li>
<li>Documentum D2</li>
<li>MDM</li>
<li>SharePoint</li>
</ul>
</aside>
$('.listlinks').each(function(){
$(this).wrapInner('<a href="\search.php?' + $(this).html() + '" />');
});
how would I add a link to each list item?
basically I have a list and i want to use js or jquery to added in href for my search page.
<aside class="listlinks">
<ul>
<li>CRM</li>
<li>CTI</li>
<li>Call Center</li>
<li>Data warehouse</li>
<li>Documentum D2</li>
<li>MDM</li>
<li>SharePoint</li>
</ul>
</aside>
$('.listlinks').each(function(){
$(this).wrapInner('<a href="\search.php?' + $(this).html() + '" />');
});
Share
Improve this question
edited Dec 18, 2015 at 18:00
Zakaria Acharki
67.5k15 gold badges78 silver badges106 bronze badges
asked Dec 18, 2015 at 17:54
Rayen KamtaRayen Kamta
2143 silver badges10 bronze badges
1
- Update: Make sure to encode the text in the url. Just remembered that.(developer.mozilla/en-US/docs/Web/JavaScript/Reference/…) – Lucas Commented Dec 18, 2015 at 18:06
4 Answers
Reset to default 3Your example would work as long as you updated the jQuery selector to match the list items instead of the parent list, e.g. replace .listlinks
with .listlinks ul li
. You should also make sure you properly encode the text in the href
portion with encodeURI
or encodeURIComponent
.
You don't really need jQuery for this and using pure Javascript and manually concatenating would save you 3-4 function calls per list item.
$('.listlinks ul li').each(function(){
this.innerHTML = '<a href="\search.php?' + encodeURIComponent(this.innerHTML) + '">' + this.innerHTML + '</a>';
});
You can shorten this even more by sacrificing one function call per list item and using String.prototype.link
. The link
method automatically wraps string objects with a hyperlink to the supplied URL.
$('.listlinks ul li').each(function(){
this.innerHTML = this.innerHTML.link('\search.php?' + encodeURIComponent(this.innerHTML));
});
$('.listlinks ul li').each(function(){
$(this).append('<a href="\search.php?' + $(this).html() + '" />');
});
You could do
$('.listlinks ul li').each(function(){
var text = $(this).html();
$(this).html('<a href="\search.php?' + encodeURIComponent(text) + '">' + text + '</a>');
});
Update: Make sure to encode the text in the url. Just remembered that
@ Rayen Kamta try this:
$.each($('.listlinks li'),function(k,v){
$(v).wrap('<a href="\search.php?' + $(v).html() + '" />');
});