2I need the thing I want to do f...">

How to remove anchor and assign anchor in html

I have ul:

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

I need the thing I want to do first li for binding.

<li>1</li>

to

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

and remove the binding from the second value

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

How to do it in jQuery?

+3
source share
1 answer

A very simple method that switches 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 need the following:

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/

+2
source

Source: https://habr.com/ru/post/1768181/


All Articles