0

I'm having an issue with inserting jQuery HTML string into HTML document, more specifically into footer of my body of the html.

The issue is when I append jQuery string which went through $.parseHTML, it appears on my screen and I can inspect it. Nonetheless, after I open View page source, I can't find it in the HTML.

let chatWindow = '<section class="module"><header class="top-bar">' + userName + '</header>';
            chatWindow += '<ol class="discussion">';

            for (let i = data[0].length - 2; i >= 0; i -= 3) {
                if (data[0][i - 1] == data[1]) {
                    chatWindow += '<li class="self"><div class="avatar"></div><div class="messages">';
                } else {
                    chatWindow += '<li class="other"><div class="avatar">';
                    chatWindow += '<img src="' + data[2] + '"/></div><div class="messages">';
                }
                chatWindow += '<p>' + data[0][i] + '</p>';
            }
            chatWindow += '<time datetime="2009-11-13T20:00"></time></div></li></ol>';
            chatWindow += '<textarea class="discussion-chat"></textarea></section>';

            chatOutput = $.parseHTML(chatWindow);
            console.log(chatOutput);

            $('.module').css('display', 'block');
            $('footer').append(chatOutput);

To clarify my clunky code, it's just a pop-up chat window which is generated through $.getJSON() function.

When I use $.parseHTML, it seems it gives me a correct format for DOM but append won't make it appear in the HTML.

Any ideas how can I insert chatWindow var into my HTML?

Thank you

1 Answers1

3

it appears on my screen and I can inspect it

Then it's working as intended.

Nonetheless, after I open View page source, I can't find it in the HTML.

Because the page source is the original source code of the page which was returned from the server. Modifications to the DOM on the client-side don't change that history.

Sounds like your code is working as designed, you're just unclear on what "View Page Source" does. It doesn't show you the current state of the DOM after JavaScript has modified it, it shows you what was returned from the server. Inspecting the DOM shows you the current state, and from your description it sounds like the current state is correct.

David
  • 208,112
  • 36
  • 198
  • 279
  • Alright, but if I have **jQuery function** which listens to `keypress` event on **.discussion-chat** text-area, which is generated by the jQuery variable, why it doesn't react? – Peter Holoubek Aug 13 '18 at 16:06
  • 2
    @PeterHoloubek: If you're trying to attach event listeners to DOM elements which don't exist yet, that's another issue entirely. It's not what you asked, but if that's the underlying problem you're trying to solve then this is the duplicate you're looking for: https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – David Aug 13 '18 at 16:12