views:

57

answers:

2

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>');";
+2  A: 

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">');
Dave Ward
It is the biggest thing there. (+1)
karim79
Thanks Dave, part of the issue did turn out to be unterminated strings :)I can't vote yet, but will do once I can
Ali
A: 

For the sake of readability, and to avoid confusing yourself like this, consider using this syntax for jQuery DOM insertion instead:

var myDiv = jQuery('#myID');
$('<span></span>').html(myDiv.html()).addClass('something').replaceAll(myDiv);

Oh, and if you look carefully at the way your code is highlighted in the question above, you can already see what you're doing wrong ;)

Yi Jiang
Thanks Yi, I am sure your above code would work (did not try it) however, I am modifying someone else's work and did not want to break consistencyand your note on highlighted code helped ;)
Ali