2

The HTML which should be produced after manipulation:

<div class="comments_action_207">
   <div class="list_item_comments list_item_comments_207">
      <div class="comment_separator">text goes here</div>
   </div>
</div>

HTML before manipulation:

<div class="comments_action_207"></div>
<div class="list_item_comments list_item_comments_207"><div class="comment_separator">text goes here</div></div>

JavaScript which allows me to do the above manipulation is:

$(function() {
    $('.comments_action_207').click(function() {
        var num = this.className.split('_').pop();
        $('</div>',{'class':'list_item_comments list_item_comments_' + num})
            .append('<div class="comment_separator">text goes here</div>')
            .appendTo(this);
    });
});

I tested the JavaScript above and it works fine. But what I don't understand is why I don't have to pass an opening div tag as below. If I pass an opening div tag code does not work as I intend to.

$('<div></div>',{'class':'list_item_comments list_item_comments_' + num}).

If you can please explain it line by line so It's is easier for me to understand.

1
  • ...When it's by itself, it's still just <div />, it's a self-closing tag, since you dont have another tag following it to close it. Commented Sep 16, 2012 at 19:13

2 Answers 2

5

Your <div> doesn't close properly:

$('<div><div/>'
            ^

jQuery accepts <div />, <div> and <div></div>, but nothing else (i.e. no HTML attributes): http://api.jquery.com/jQuery/#jQuery2

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

5 Comments

Really? I'll have to add that in. Thanks!
sure it is: jsbin.com/omujik/1/edit and also: <div/> (without the space lol) +1
Actually it does accept the map containing HTML attributes...or am I misunderstanding your post?
@Dasun: <div><div/> is not valid HTML, while <div></div> is correct. I am sure you already know it. You just misplaced the / character. In other words: you can pass the opening div tag... you just need to do it right.
Oops that is a typo. I'm sorry about it.Thanks for the answer
0

Please try this ...It will work

$('<div></div>',{'class':'list_item_comments list_item_comments_' + num})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.