user2789240 user2789240 - 2 years ago 82
Javascript Question

jQuery, Ajax: Unable to replace HTML

There's a button on a webpage. When clicked, it will replace paragraph (

) with header (

However, I can't seem to make it worked:


<script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
<script src="js/libs/jquery/jquery.js"></script>
<script src="js/libs/jqueryui/jquery-ui.js"></script>
<script src="js/main.js"></script>
<p id="replaceableP1">This text will be replaced </p>
<button id="myButton">Get External Data</button>



$.get("someInfo.html", function (data, status){
if (status === "success"){
} else {
$("#replaceableP1").html("Problem reading data");



<h1>This is external data!</h1>

The error generates on:
in the main.js

If I replace
, it will replace element index.html and displayText.

If I remove someInfo.html from the directory, the webpage won't even generate error message: Problem reading data.

What's wrong with the code?

EDIT: My bad, I forgot there is

Answer Source

There are two things that I see. The first is that you have an extra "});" in your main.js file. The second is that .html will replace the inner HTML of the selected element. If you want to replace the <p> with the <h1>, you would use .replaceWith.

For example,

$(document).ready(function() {

    $.get("someInfo.html", function(data, status) {
        if (status === "success") {
        } else {
            $("#replaceableP1").html("Problem reading data");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download