I tried to do this for replacing a paragraph with a text area with the same content.
function edit() {
var wdith = $("p").css('width')
$("p:first").replaceWith("<textarea class='edit'>" + $("p:first").text() + "</textarea>")
$(".edit").css("width", wdith)
}
$("#replace").click(edit);
Demo
But it doesn't work correctly. There are spaces before and after the text.
How do I fix it?
You script is doing as it says on the tin. You're getting spaces because you have spaces and line breaks within your <p>
tags.
To remove the text formatting, try this: http://jsfiddle.net/z9xCm/18/
function edit() {
var wdith = $("p").css('width');
var p = $("p:first");
var t = p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim();
p.replaceWith("<textarea class='edit'>" + t + "</textarea>")
$(".edit").css("width", wdith)
}
$("#replace").click(edit);
First, we remove the line breaks, then removed multiple repeated spaces, then trim spaces at the beginning and end of the text.
Somewhat off topic, but that can also be rewritten as : http://jsfiddle.net/z9xCm/52/
$("#replace").click(function() {
var p = $("p:first");
p.replaceWith($("<textarea/>", {
"class": "edit",
"text": p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim(),
"css": { "width": p.css('width') }
}));
});
Here's the same thing, but in a less compact and commented form.
$("#replace").click(function() { /* assign anonymous function to click event */
var p = $("p:first"); /* store reference to <p> element */
/* get p.text() without the formatting */
var t = p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim();
/* create new textarea element with additional attributes */
var ta = $("<textarea/>", {
"class": "edit",
"text": t,
"css": {
"width": p.css('width')
}
});
p.replaceWith(ta); /* replace p with ta */
});
Note that the $("...", {...})
syntax for creating new elements with attributes was only introduced in jquery 1.4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With