Search code examples
javascriptjqueryhtmlcontain

Jquery remove link with a certain label and the whole text after this link


For example:

<a href="/" title="Go to homepage">Homepage</a> text after link;
<a href="/" title="About">About</a> text after link;
<a href="/" title="Contact Us">Contact Us</a> text after link;

No problem: I can remove the link with:

$("a:contains('Homepage')").remove();

My question: How to remove the text after the link previously removed:

text after link

Thanks in advance.


Solution

  • You can set that text node's value to empty, like this:

    $("a:contains('Homepage')")[0].nextSibling.nodeValue = "";
    

    You can try it here. If you're unsure if it's there, add an if check, like this:

    var node = $("a:contains('Homepage')")[0];
    if(node && node.nextSibling) node.nextSibling.nodeValue = "";