Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
klam tine
15,524 PointsJavaScript DOM selection
Hi Everyone,
Make it short: I found out when I'm using dom insertion like createElement and append it to the Node, things like declaring html elements in JS, I can't handle them.
For Example:
$('#container').append('<button class="act">Hello Teamtrehouse</button>');
$('.act').click(function () {
$('body').hide();
} )
When I click the button, failed, nothing happens. I hacked it with writing Javascript in the HTML tag like this
<button onclick="something"></button> (NOT RECOMMEND)
I suppose it's because I created some elements after the DOM tree built. How to solve this and why this happened?
Thank you. Michael
2 Answers
Chris Akers
2,527 PointsYour method appears to work for me: http://jsbin.com/eKaqOBi/2/quiet
But I put an alternate method in that bin that you could try.
klam tine
15,524 PointsIt's solved last night. (I'm Chinese)
$('#container').append('<button class="act">Hello Teamtrehouse</button>');
$('#container').on('click', '.act', function () {
$('body').hide();
} )
And it works A-OK. In jQuery it's named Delegate [http://api.jquery.com/on/]
klam tine
15,524 Pointsklam tine
15,524 PointsTks, that works better than hack directly in HTML.
But same problem, our methods are too "tight"(Sorry I'don know how to express it in English)
For example the JS is combined too tight and exactly to the HTML, if somewhere changed(very generally), both sides have to make a change or it won't work, and you, the programmer have to change it one by one manually.
In order to make life easier, I fond a method and write below.
Thanks again
Chris Akers
2,527 PointsChris Akers
2,527 PointsI understand what you're saying by "tight". And delegation is a great way to decouple common functionality from the elements. Good job Michael!