Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Append JavaScript to a Div

I'm using jQuery to append some JavaScript when an item is expanded.

But the JavaScript code inside of the jQuery function is causing the rest of the jQuery code to explode.

$(this).parent('li').find('.moreInfo').append('<script>alert("hello");</script>');

What can I do to solve this problem?

like image 461
Tim Avatar asked Jun 07 '09 05:06

Tim


People also ask

Can you append to a div in JavaScript?

In JavaScript, we can append HTML code to a div using innerHTML and insertAdjacentHTML.

How append a div in another div using jQuery?

First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.

What is insertAfter in jQuery?

The insertAfter() method is an inbuilt method in jQuery that is used to insert some HTML content after a specified element. The HTML content will be inserted after each occurrence of the specified element. Syntax: $(content).insertAfter(target)


1 Answers

For the appending JavaScript problem use this:

var str="<script>alert('hello');";
str+="<";
str+="/script>";

$(this).parent('li').find('.moreInfo').append(str);

Otherwise a better option will be to wire-up li's click event:

 $("ul#myList li").click(function(){
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "url to your content page",
            data: "{}",//any data that you want to send to your page/service
            dataType: "json",
            success: function(msg) {
                $(this).find('.moreInfo').append(msg);
            }
        });
 });

Actually I don't know what language are you using. If you are using ASP.NET please read this blog by Dave.

like image 113
TheVillageIdiot Avatar answered Sep 21 '22 00:09

TheVillageIdiot