Adrin
Adrin

Reputation: 595

append a div to body and a script to the div

I'm trying to append div to the body and then append a script to the div. so here is my code:

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

        var $div = $('<div/>').appendTo('body');
        $div.attr('class', 'div-bla');

        var $script = $('<script/>').appendTo('div-bla');
        $script.attr('text', 'alert('yay')');

    }); 
});

but it's not working at all, what is wrong here?

Upvotes: 2

Views: 67

Answers (2)

Hackerman
Hackerman

Reputation: 12305

You are almost there:

$(document).ready(function() {
  $("#btn").click(function(){
     var $div = $('<div/>').appendTo('body');
     $div.attr('class', 'div-bla');

     var $script = $('<script/>').appendTo('.div-bla');
     $script.text('alert("yay")');
   }); 
});

Upvotes: 2

Dacre Denny
Dacre Denny

Reputation: 30360

There are a few ways to resolve this - one option is to pass the $div to the appendTo() method directly like so:

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

        var $div = $('<div/>').appendTo('body');
        $div.attr('class', 'div-bla');

        var $script = $('<script/>').appendTo($div); // <-- Update this line
        $div.attr('text', 'alert("yay")'); // <-- also update this line to avoid a syntax error

    }); 
});

Upvotes: 1

Related Questions