“Transform” one element into another with JQuery

Posted on

Question :

In my script, I have a iframe .

<iframe id="result" name="result" src="url_do_documento" sandbox="allow-same-origin"></iframe>

The file that iframe references, contains a h1 element, as in the structure below:

    <h1 class="pf-change-h1">H1 que pretendo alterar!!</h1>

To access h1, I’m using JQuery as follows:

    var h1 = $("#result").contents().find(".pf-change-h1");
        $(this).replaceWith("<input type='text' value='" + $(this).html()  + "' class='pf-change-h1' />");
        $(this).replaceWith("<h1 class='pf-change-h1' >" + $(this).html()  + "</h1>");

The purpose of this code would be to replace the element h1 with a input , so that its value could be changed, then altered should happen exactly the inverse.

The commented code is what just is not working, the onBlur event is not triggered and input is not replaced by h1 .

Does anyone have any idea how to do this element replacement?


I tried both forms of the answers and did not get the expected result: /

When viewing code execution through the browser console, h1 has an event bound to it, as you can see:



Answer :

I think the problem here is that you are re-writing h1, and you lose the reference when you replace it … the solution that occurs to me is to rename this new element before you have to reference it. I suggest you also use delegation for this. In that case it would look like this:

    var blur = function () {
        $(this).replaceWith("<h1 class='pf-change-h1' >" + this.value + "</h1>");
    $("#result").contents().on('click', ".pf-change-h1", function () {
        var input = $("<input type='text' value='" + ($(this).html() || this.value) + "' class='pf-change-h1' />");

jsFiddle: link

Notice that I replace $(this).html() to this.value , same as $(this).val() , since input elements do not have innerHTML


What happens is that replaceWith destroys the element, so the event is lost. It is then necessary to re-associate the events with the element. Since you are working with a iframe , I do not know how the scope is, but the idea is more or less the following:

function h1_click() {
    $(this).replaceWith("<input type='text' value='" + $(this).html() + "' class='pf-change-h1' />");
    $(".pf-change-h1").blur(function () {
        $(this).replaceWith("<h1 class='pf-change-h1' >" + $(this).val()  + "</h1>");

    var h1 = $("#result").contents().find(".pf-change-h1");


Leave a Reply

Your email address will not be published. Required fields are marked *