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:

(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>

Leave a Reply