lgt
lgt

Reputation: 1034

Jquery removing and changing html tags

I have couple of hyperlinks on my website. What I want is to remove the a href html tag if they match with a given condition.

Example

if href is example.com then, hyperlink should be dissolved and <a></a> tag should disappear

I have been using the following statement,

$("a[href='http://www.example.com']").removeAttr("href"); 

the href is going to be removed but <a> is still there.

Upvotes: 1

Views: 113

Answers (7)

Amritpal singh
Amritpal singh

Reputation: 865

You can remove the whole tag with :

$("a[href='http://www.example.com']").find().remove();

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237895

The nicest way to do this is with contents and unwrap:

$("a[href='http://www.example.com']").contents().unwrap();

This says:

  • find all the links that match the selector
  • get all their child nodes
  • unwrap the child nodes from their parent, i.e. replace the a element with its child nodes

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34107

Demo http://jsfiddle.net/3utk7/

code

$('a').each(function() {
    var foo = $(this).attr("href");
    if (foo == "http://www.example.com") {
        $(this).remove();

    }
});​

Upvotes: 0

cdxf
cdxf

Reputation: 5648

$("a[href='http://www.example.com']").remove(); 
$("a[href='http://www.example.com']").unwrap(); -> also check this :D 

Upvotes: 1

Alnitak
Alnitak

Reputation: 339836

To preserve the link's text, but remove the link itself:

$("a[href='http://www.example.com']").replaceWith(function() {
    return $(this).text();
});

use .html() instead if there are other HTML tags within the link that you wish to preserve.

Upvotes: 2

xdazz
xdazz

Reputation: 160853

You could use .remove to remove the whole element.

$("a[href='http://www.example.com']").remove();

Upvotes: 3

nnnnnn
nnnnnn

Reputation: 150040

To remove the anchor element try this:

$("a[href='http://www.example.com']").remove();

For more info see the.remove() doco.

EDIT: To replace the anchor element with its content try this:

$("a[href='http://www.example.com']").replaceWith(function() {
    return $(this).html();
});

The .replaceWith() method does what you might expect. If you pass it a function then that function will be called for each matching element, with this being the current element that will be replaced by the return from the function.

Upvotes: 1

Related Questions