Reputation: 1915
I have <ul>
list with <a>
links. I would like to find the <li>
WITHOUT <a>
and wrap a <a>
to it.
How can I check if the <li>
has no <a>
(in this case <li>hello</li>
)?
<ul class="sorter">
<li>
<a href="url">blabla</a>
</li>
<li>
hello
</li>
</ul>
Upvotes: 1
Views: 118
Reputation: 5178
You can use :not and :has for this:
$(document).ready(function()
{
$("ul.sorter li:not(:has('a'))").each(function()
{
$(this).append('<a href="#">added</a>');
});
});
Update To wrap <li>
text with <a>
:
$(document).ready(function()
{
$("ul.sorter li:not(:has('a'))").each(function()
{
$(this).html('<a href="#">' + $(this).text() + '</a>');
});
});
Upvotes: 6
Reputation: 187
You can use JQuery for it.
add the following line in the head of your html
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
then at the end of the body add the following
<script>
$( document ).ready(function() {
$('body ul').find('li').each(function(){
var isA = $(this).find('a');
if(isA.length == 0){
$(this).append('<a href="#">Lorem Ipsum</a>');
}
});
});
</script>
Upvotes: 1
Reputation: 1750
$(".sorter li").each(function(){
var li = $(this)
var a_tag = li.find('a');
//without <a> tag
if( a_tag.length == 0 ){
//keep content in <li>
var li_txt = li.html();
//add <a> tag
li.html('<a href="#">' + li_txt + '</a>');
}
});
Fiddle
Upvotes: 1