user2636556
user2636556

Reputation: 1915

Select the <li> without <a>

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

Answers (3)

Regent
Regent

Reputation: 5178

You can use :not and :has for this:

Fiddle

$(document).ready(function()
{
    $("ul.sorter li:not(:has('a'))").each(function()
    {
        $(this).append('<a href="#">added</a>');
    });
});

Update To wrap <li> text with <a>:

Fiddle

$(document).ready(function()
{
    $("ul.sorter li:not(:has('a'))").each(function()
    {
        $(this).html('<a href="#">' + $(this).text() + '</a>');
    });
});

Upvotes: 6

R A Khan
R A Khan

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

Parfait
Parfait

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

http://jsfiddle.net/c0ukahzn/

Upvotes: 1

Related Questions