Tomáš Messing
Tomáš Messing

Reputation: 3

How to insert HTML text to jQuery

I'm learning JavaScript and jQuery. What am I doing wrong here? It will create window but not insert text. Thank you for your help

Script:

$(document).ready(function(){
    $('.button7').click(function(){
        $('#page').append('<div id="window"></div>');
            $("#window").load("pages/window1.html");
    });
});

HTML:

<div class="window1">
    <p style="color: white">HELLO WORLD!</p>
</div>

next problem is that it dont want to load html file

    $(document).ready(function() {
   $('.button7').click(function() {
     $('#page').append('<div id="window">NEW DIV ADDED</div>');
     $("#page").find("div").on("ondivload", function() {
       $("#window").load("window1.html", function() {
         alert("now external html loaded");
       });
     });
     alert("now div#window appended");
     $("#page").find("div").trigger("ondivload");

   });

 });

Upvotes: 0

Views: 247

Answers (3)

Arindam Nayak
Arindam Nayak

Reputation: 7462

You can use .html() and .text() to insert html and text content respectively to target control/element. And also you can use .load() to get content of external html file to control.- Note: this will be a GET request to external file and it has callback convention.

.html and load example. Click html to append a div with id = window and after appending , it will load html into that div window.

 $(document).ready(function() {
   $('#btn').click(function() {

     $('.page').append('<div id="window">NEW DIV ADDED</div>');
     $(".page").find("div").on("ondivload", function() {
       $("#window").load("http://www.w3.org/TR/html4/index/elements.html", function() {
         alert("now external html loaded");
       });
     });
     alert("now div#window appended");
     $(".page").find("div").trigger("ondivload");

   });

 });
 .page {
   border: 5px #CCC solid;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" value="HTML" id="btn" />
<div class="page">
  OLD Content
</div>

Upvotes: 2

Edwin
Edwin

Reputation: 825

You have this: <p style="color: white">HELLO WORLD!</p>

Unless your background color is not white, change the color to any color other than white if you want to see the text. color is to change text color.

Also, you've not added .button7 and #page to the HTML

DEMO

Upvotes: 0

Avinash Babu
Avinash Babu

Reputation: 6252

You can simply use the .html() method which get the HTML contents of the first element in the set of elements.

If you want to insert just text you can use the function .text().

Upvotes: 1

Related Questions