Search code examples
javascriptjqueryvariablessplithref

Splitting an href and putting the html into a variable


I want to send this HTML, minus "/modal" into a variable:

<span class="detailsLink"><object><a href="/content/modal/30OffLucky" class="js-modal btn-secondary">DETAILS</a></object></span>

How can I add to this line to make it work?:

var eemailDetails = $('.detailsLink').html();

This ends up taking out /modal before it passes it into the variable:

var eemailDetails = $('.detailsLink a').each(function(){
    this.href = this.href.replace('/modal', '');
}).html();

Thank you for your time!


Solution

  • The replacement should be made on the value retrieved instead of on the element's attribute.

    So to retrieve the HTML markup including the targeted element, the outerHTML property can be used.

    // Get the whole HTML
    var eemailDetails = $('.detailsLink')[0].outerHTML;
    
    // Remove /modal
    eemailDetails = eemailDetails.replace('/modal', '');
    
    
    console.log("The attribute unchanged: "+$('.detailsLink a').attr("href"));
    console.log("The HTML retrieved: "+eemailDetails);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <span class="detailsLink"><object><a href="/content/modal/30OffLucky" class="js-modal btn-secondary">DETAILS</a></object></span>