0

I dynamically change the HTML content. But when I change the content, all the CSS styling is removed. How can I keep the CSS style when I change the content dynamically?

<div id="sample">
    <a href="#" onClick="call()">Change it </a>
    <p id="para"> I am paragraph </p>
</div>
p {
    background-color: yellow;
}
function call(){    
    $("#para").replaceWith('oops css gone');
} 

Here is the jsFiddle: http://jsfiddle.net/rajagopalx/6sbvtpp6/

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
rajagopalx
  • 3,012
  • 9
  • 41
  • 52

5 Answers5

7

The issue is because you're replacing the entire p element with a textNode. Instead, just change the text of the initial p element by using the text() method:

function call(){    
    $("#para").text('oops css gone');
}  

Updated fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0
function call(){    
    $("#para").replaceWith( '<p id="para">oops css gone</p>');

}

Don't forget to replace your tags as well.

Sam Kennedy
  • 95
  • 1
  • 7
0

If you replacing the element with a new one you could store the classnames and replying them to the new element.

.highlight {
    background-color: yellow;
}
----------------------------------------------
var replacedElement = $("<div />");
var storedClass = $("#para").attr("class");

replacedElement.text("yeah css still there");   
replacedElement.attr("class",storedClass);

http://jsfiddle.net/6sbvtpp6/2/

Type-Style
  • 1,791
  • 1
  • 16
  • 35
0

you can also use .html() function of jquery

function call(){    
    $("#para").html( 'oops css gone');
}  
Hassan
  • 251
  • 1
  • 14
0

.replaceWith replaces the entire element. There are many ways to go about it. Simplest of all is, either go for :

 function call(){    
        $("#para").text( 'oops css gone');
    }  

    or

    function call(){    
        $("#para").html( 'oops css gone');
    }  

There is this SO link for an understanding on the difference between .text() and .html()

Community
  • 1
  • 1
King Size
  • 397
  • 1
  • 6