tags:

views:

39

answers:

1

i have a ul

<ul>
<li>1</li>
<li><a href="#">2</a></li>
</ul>

i need a thing that i want to make first li to anchor means

<li>1</li> to <li><a href="#">1</li></li>

and remove anchor from 2nd means

 <li><a href="#">2</a></li>  to <li>2</li>

how i can do this in jqeury

+2  A: 

Very simple method, that "toggles" the links:

$('ul li').each(function() {
    if($(this).find('a').length > 0) {
         $(this).text($(this).text());
    }
    else {
        $(this).html($('<a />').attr('href', '#').text($(this).text()));
    }
});

Example: http://jsfiddle.net/E2ryt/

Update:

From your comment I think you want this:

$('ul li').each(function() {
    $(this).html($('<a />').attr('href', '#').text($(this).text()));
}).click(function() {
     $(this).text($(this).text());
});

But I'm not 100% sure. See here: http://jsfiddle.net/E2ryt/1/

Update 2:

Based on David's comment, you might want this:

var lastClicked = null;

$('ul li').click(function() {
    if(lastClicked) {
        lastClicked.html($('<a />').attr('href', '#').text(lastClicked.text()));
    }
    lastClicked = $(this).text($(this).text());
});

See here: http://jsfiddle.net/E2ryt/2/

Felix Kling
+1. Should be noted however that if there's a jQuery listener for those links, `.live("click", function() { ...` should be used instead of `.click(function() {...` Had my fair share of head-to-desk action because of that :)
FreekOne
i thing you confused i want to make all li to anchor and on clicked li anchor will be removed.
steven spielberg
@steven: So you want to remove the link if it was clicked? You did not mention this in your question. You just said you want to transform no-links to links and links to no-links. What do you really want? Can you please clarify?
Felix Kling
@Felix: I don't have the details, but it's starting to look as though mr spielberg wants a menu-like behavior, where only the just-clicked link isn't clickable.
David Hedlund
@David: Ah good idea... :) *thumbs up*
Felix Kling