Search code examples
jqueryquotesdouble-quotes

Using <div class="something"> inside a jQuery replaceWith() function


I am working on a PHP document which has jQuery code in it. I am using a replaceWith() functions to strip outer divs and replace with span. it seems I can only replace it with <span> and not <span class="something">

Why is that?

Edit: Here is an example of the code:

Thanks Dave, but I actually use the second option in your code above, here is what I am trying to do:

$response[] = "jQuery('#myID').replaceWith('<span>'+jQuery('#myID').html()+'</span>');";

The above code works. Basically, I have an <a> element I want to replace with a <span> element and change the class on an ajax response.

Now, if I add classes to any of the spans above:, like this:

$response[] = "jQuery('#myID').replaceWith('<span class"something">'+jQuery('#myID').html()+'</span>');";

the code breaks, is it because of the outer double-quotes on the jQuery statement?

Edit

So it turned out to be an issue with my <a> element I was trying to replace, in addition to escaping the double-quotes around the class :). Thanks for the extremely prompt help. I am registering to give credit where credit is due :)

$response[] = "jQuery('#myID').replaceWith('<span class=\"something\">'+jQuery('#myID').html()+'</span>');";

Solution

  • Since the biggest change there is the addition of quotes, double check that the class attribute isn't leaving an unterminated string open:

    // Broken:                 
    $("div").replaceWith("<span class="something">");
    
    // Fixed:
    $('div').replaceWith('<span class="something">');