Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can a wrap the content of an element with a <a> tag with the help of jQuery

I have following setup:

<div class="vc_acf organisation">
    <span class="vc_acf-label">Organisation:</span> CLEMI</div>
</div>

I want to change it in:

<div class="vc_acf organisation">
    <span class="vc_acf-label">Organisation:</span> <a href="https://beglobal.toc-web.site/resources/clemi">CLEMI</a></div>
</div>

What I got so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(function($) {
    $(".organisation").each(function() {
        $(this).html($(this).html().replace(/CLEMI/g, "<a href='https://beglobal.toc-web.site/resources/clemi'>CLEMI</a>"));
    });

})(jQuery);

This works perfectly but I have dozens of organizations (like CLEMI is one of them). The field .organisation is dynamically created and always changes. So I don’t want to write the jQuery for every organization but find a shortcut to select the content of that element and wrap it a link and also change the url of that link.

*Note sometimes the organization exists of two word, for example: SOS Faim the link should be then: https://beglobal.toc-web.site/resources/sos-faim

>Solution :

This could be solution to your problem

(function($) {
    $(".organisation").each(function() {
        // Get span label
        var span = $(this).find(".vc_acf-label")[0].outerHTML;
    
        // Get company name
        var text = $(this).text();
        text = text.replace("Organisation:","").trim();
        
        // Make link from company name
        var href = text.trim().replace(" ", "-");
        href = "https://beglobal.toc-web.site/resources/" + href.toLowerCase();
      
       $(this).html(span + " <a href='"+ href +"'>"+ text +"</a>");
    });

})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="vc_acf organisation">
    <span class="vc_acf-label">Organisation:</span> CLEMI
</div>
<div class="vc_acf organisation">
    <span class="vc_acf-label">Organisation:</span> SOS Faim
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading