I have a unordered list with links and sublinks. I'd like to prepend a '»'
character in front of the sublinks in the list. I could probably do this with CSS via list-style-image:url
but I'd rather just have text. So far I have tried prepend without much success.
HTML:
<nav>
<ul>
<li><a href="#">link 1</a></li>
<li><a href="#">link 2</a></li>
<ul>
<li><a href="#">sublink link 1</a></li>
<li><a href="#">sublink link 2</a></li>
</ul>
<li><a href="#">link 3</a></li>
</ul>
</nav>
And I am using this code:
$("ul li li").each(function() {
$(this).closest('li').prepend("»").html();
});
If I take away one level of list items and prepend to all list items, then it works but viewing in web inspector, the »
character still has quotes around it. I also tried various incarnations of what appeared for closest such as li a
but that did not make a difference either. I'm not getting any syntax errors so not sure what I am doing wrong.
I have a Fiddle here.
I have a unordered list with links and sublinks. I'd like to prepend a '»'
character in front of the sublinks in the list. I could probably do this with CSS via list-style-image:url
but I'd rather just have text. So far I have tried prepend without much success.
HTML:
<nav>
<ul>
<li><a href="#">link 1</a></li>
<li><a href="#">link 2</a></li>
<ul>
<li><a href="#">sublink link 1</a></li>
<li><a href="#">sublink link 2</a></li>
</ul>
<li><a href="#">link 3</a></li>
</ul>
</nav>
And I am using this code:
$("ul li li").each(function() {
$(this).closest('li').prepend("»").html();
});
If I take away one level of list items and prepend to all list items, then it works but viewing in web inspector, the »
character still has quotes around it. I also tried various incarnations of what appeared for closest such as li a
but that did not make a difference either. I'm not getting any syntax errors so not sure what I am doing wrong.
I have a Fiddle here.
Share Improve this question edited Sep 17, 2012 at 22:08 Ram 145k16 gold badges173 silver badges201 bronze badges asked Sep 17, 2012 at 21:58 Danny EnglanderDanny Englander 2,0445 gold badges27 silver badges41 bronze badges 05 Answers
Reset to default 4Why not some css?
ul ul li:before {
content: '»';
}
Using JavaScript to modify the UI for something like this is a waste of resources. This is subjective without knowing your actual use case.
Your selector is not correct, also there is no need to use html
and each
methods.
$("ul ul li").prepend("»");
You had an incorrect selector ul li li
implied there was an li
directly within an li
but there is another ul
between.
In addition you don't need to use a .each
for that as jQuery will return the reference to the set of elements which matched the selector.
$("ul ul li").prepend("»");
DEMO
Mind you the CSS solution from Aknosis
looks very cool.
I think this is what you are needing:
$("ul ul li").prepend("» ");
Try:
$("ul li").each(function() {
$(this).prepend("»").html();
});