1

I got a question in theory... I'm currently at work and can't try it..

If I have the following code :

stuff = '<button onclick="alert(' + "'Test');" + 'my Button</button>'; $("container").html(stuff); 

When I click on my new button, will my script work? And will my button be added?

I didn't get any result on JsFiddle...

12
  • 1
    your selector "container" is probably wrong, to start with. Please link to the fiddle. Commented Mar 22, 2013 at 17:29
  • possible duplicate of Can scripts be inserted with innerHTML? Commented Mar 22, 2013 at 17:30
  • 1
    I would consider binding the event in JavaScript, in addition to fixing your tag: $("container").replaceAll($("<button>my Button</button>").click(function () { alert("Test"); })); Commented Mar 22, 2013 at 17:32
  • @bfavaretto The quotes look fine. That's the reason he alternates single and double quotes, presumably because he doesn't know how to backslash-escape them. The problem is actually the missing >. Commented Mar 22, 2013 at 17:49
  • 1
    @bfavaretto Yes, that's true too. But it's not a problem due to incorrect escaping. :) Of course, there is weird escaping, but not incorrect escaping. Commented Mar 22, 2013 at 17:52

3 Answers 3

3

Supposing you fix the selector "container" and the unclosed tag, it should work.

But that's not how you bind events properly using jQuery.

You should do this :

$("#container").empty().append( $('<button>my Button</button>').click(function(){ alert("Test") }) ); 
Sign up to request clarification or add additional context in comments.

2 Comments

After reading the docs, I don't think replaceAll nor replaceWith does the right thing. I was looking for a method that replaces all child elements with the elements in the supplied query. I think the only way to do that is $("#container").empty().appendTo(...). I believe this is what we want in this case to replace .html(...).
And good call on editing to use append() instead of appendTo(), as I mistakenly said. After looking at jQuery docs all day you get these methods confused with each other...
2

It would work if you closed the opening button tag correctly

stuff = '<button onclick="alert(' + "'Test');" + '">my Button</button>'; $("container").html(stuff); ^^ 

Also as pointed out in a comment your selector for container is probably wrong.

Most likely you want one of these 2 depending on if container is a class or id:

$(".container").html(stuff); $("#container").html(stuff); 

Comments

0

That would work, but you forgot to close your button tag.

stuff = '<button onclick="alert(\'Test\');">my Button</button>'; $("container").html(stuff); 

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.