Search code examples
jquerytextareahrefeach

jQuery - loading textarea, adding suffix to every href and displaying the result


I'm trying to get a bit of jQuery working. It needs to select some html code from a textarea, add a suffix to every href within it and then display the resulting html code in another textarea. I don't want it to ever render the HTML, just display the code.

Here's where I've got to...

$('#apply').click(function() {
    var a = $('#a').val();
    var b = $('#b').val();
    var c = $('#c').val();

    var query_string = '?a=' + a + '&b=' + b + '&c=' + c;

    var input_html = $("#input_html").val();

        $(input_html + ' a').each(function() {
            var href = $(this).attr('href');

            if (href) {
                href += (href.match(/\?/) ? '&' : '?') + query_string;
                $(this).attr('href', href);
            }
        });

    $("#output_html").val(input_html);
});

It should be simple enough and I think I'm pretty close but I've got a complete mental blank about why it's not working. Anyone care to find where I've gone wrong?

UPDATE 04/11/2016

Thanks for the answer but it breaks with nested code, e.g. try this...

<table><tr><td><a href="foo-bar"><img src="image.jpg"></a></td></tr></table>
<a href="foo-bar"><img src="image.jpg"></a>

The first link will not have the query string, the second will?


Solution

  • Your input_html var is a text string - you need to parse it into DOM objects before you can check for anchor tags and play with their hrefs.

    Once you've done that you can modify them, then turn them back into HTML for your output.

    The sample below handles a few different cases - although there is an odd behaviour when the anchor has a blank href

    $('#apply').click(function() {
        var a = $('#a').val();
        var b = $('#b').val();
        var c = $('#c').val();
    
        // don't need the ? here, we add it later
        var query_string = 'a=' + a + '&b=' + b + '&c=' + c;
    
        var input_html = $("#input_html").val();
        
        // parse string into HTML DOM objects
        var html_dom = $.parseHTML( input_html );
    	
        // create a new var to store our new output
      	var output_html = '';
        
        // loop over DOM objects, check for anchor tags
        $.each( html_dom, function( i, el ) {
    
          if( el.nodeName === 'A' ) {
          
              // if we have an anchor, get it's href
              var href = el.href;
    
              // if it's not blank, append query
              if ( href != '' ) {
                el.href += (href.match(/\?/) ? '&' : '?') + query_string;
              }
          }
          
          // append the element as html to the output string
          // here we make a div $(<div/>)
          // inject the element ,append($(el))
          // then ask jQuery to give the contents as HTML .html()
          output_html += $('<div/>').append($(el)).html();
        });      
    	
        // put the html in the output cell
        $("#output_html").val( output_html );
    });
    textarea {
      width: 100%;
      height: 8em;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    A<input id="a" value="a" /><br/ >
    B<input id="b" value="b" /><br/ >
    C<input id="c" value="c" /><br/ >
    <textarea id="input_html">
      <a href="http://example.com">Link</a>
      <a href="http://example.com?foo=bar">Link</a>
      <p>Other elements get ignored</p>
      As does plain text
      <a href="">Blank Href</a>
      <a class="foo">No Href</a>  
    </textarea>
    <textarea id="output_html"></textarea>
    <button id="apply">Apply</button>