9

I'm trying to append a piece of text to a div using jQuery. I try to do this using the following code:

<html><head></head><body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#sendButton").click(function(){
            $("#conversation").append("<P>This is a message");
        });
    });
</script>
<div class="conversation"><p>some message</div>
<form><input type="button" id="sendButton" value="Send Message"></form>
</body></html>

Seeing the multitude of tutorials on the subject it seems to be such a simple thing to do, but I can't seem to figure out what I'm doing wrong here. Any help would be greatly appreciated.

3
  • 1
    You can't append partial elements, and you shouldn't have unclosed elements in your HTML either ? Others will soon point out that the selector is wrong as well. Commented Feb 5, 2014 at 18:26
  • 1
    @adeneo: The p element: A p element's end tag may be omitted if the p element is immediately followed by an address, article, aside, blockquote, div, dl, fieldset, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, main, nav, ol, p, pre, section, table, or ul, element, or if there is no more content in the parent element and the parent element is not an a element And the <input> element is a void element which doesn't need an end tag (and the / is optional) Commented Feb 5, 2014 at 18:41
  • @Andreas - That's why I wrote "shouldn't", as you can omit the closing P tag, but in javascript you simply can't, jQuery fixes this and uses innerHTML, createElement, appendChild internally (depending on the method), and in javascript there's no such thing as an unclosed element, with the exception of self closing elements, so appending half an element is just plain wrong, even if the parser inserts the closing P tag for you. Commented Feb 5, 2014 at 19:10

3 Answers 3

13

You need to use class selector, As #conversation referes to element with id conversation

 $(".conversation").append("<P>aergerag");

Fiddle DEMO

EDIT

You should look at this To Close or Not To Close Tags in HTML5 and a good question Closing tags in HTML5

Sign up to request clarification or add additional context in comments.

Comments

4

replace # with . in your selector (conversation is a CLASS)

$(".conversation").append("<P>aergerag");

Comments

0

I am not any good at jQuery but from one of my projects I had to simply target the div with html as: var someData = "This is a message"; $("#conversation").html(someData);

If some contents exists before this, then you can retrieve them, concatenate, and write it back into the target div.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.