简体   繁体   中英

How to disable an anchor (link) tag (convert to span)

I have a bunch of anchor tags ( <a> ) that I need to convert to <span> tags. I don't need to do this to disable clicking (I know about preventDefault() and returning false from the click event handler). I just need to do this to enable drag and drop sorting (which IE forbids on an anchor tag but permits on a span).

I have a working solution that is fine.

http://jsfiddle.net/5HGbx/

I'm just wondering if any of you wizards have a slicker way of achieving the same end result.

you could use replaceWith from jQuery API

$('#myButton').click(function(){
    $("#someDiv a").replaceWith(function(){
        return $("<span>" + $(this).html() + "</span>");
    });
});

Fiddle here: http://jsfiddle.net/naveen/ufYCt/1/

Mixing standard DOM methods with jQuery is a bit odd and unnecessary. You could just do something like this instead:

function aToSpan() {
    var $link = $('a');
    var $span = $('<span>');
    $link.after($span.html($link.html())).remove();
}

This just copies the link's content to a new <span> and then replaces the <a> with the new <span> .

References:

from the naveen's answer you will lose the href tag

if you want href tag too just modify this as follows...

$('#myButton').click(function(){
    $("#someDiv a").replaceWith(function(){
        return $("<span href=\""+$(this).attr('href')+"\">" + $(this).html() + "</span>");
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM