Search code examples
jqueryhtmltexthyperlinkhref

How can get the HTML of an anchor selected by its text string?


Is there a way to get code behind a content in jQuery, like <a href="http://www.example.com" class="link">Text</a>

So i need something like: if ($(".link").text() == "Text"){alert("<a href="http://www.example.com" class="link">Text</a>");}

The thing is that i need to get the text from alert(); from page, and maybe some code before.


Solution

  • Given this link:

    <a href="http://www.example.com" class="link">Text</a>
    

    ... you can get its HTML like so:

    var myLink = $('a:contains("Text")')[0].outerHTML;
    

    ... and then do with it what you will.

    alert(myLink);
    

    Demo

    Read more


    Here's how you'd get the anchor's parent element as well:

    var myLink = $('a:contains("Text")').parent()[0].outerHTML;
    

    Demo


    Aaaaaaand, to add a class to the outer element, you could do this:

    var myLink = $('a:contains("Text")').parent();
    
    $(myLink).addClass('my-class');
    
    var myLinkHtml = $(myLink)[0].outerHTML;
    

    Demo