Hey guys, I have some code that I found that I would rather use as jQuery instead of direct JavaScript. Hopefully you guys can help me convert it:
var sub = document.getElementById('submit');
sub.parentNode.removeChild(sub);
document.getElementById('btn-area').appendChild(sub);
document.getElementById('submit').tabIndex = 6;
if ( typeof _some_var != 'undefined') {
document.getElementById('some-textarea').value = _some_var;
}
document.getElementById('something').style.direction = 'ltr';
The reason I want to do this is because FireFox is telling me that sub is null when it is used on the second line. This happens because that code runs before the the submit button appears. So naturally I would like to use jQuery for the purpose of running the code after everything is ready. Yes, I know it's possible to do that in direct JavaScript as well, but I would rather have jQuery either way.
Thanks!
-
You don't have to call removeChild because when you use appendchild it will first remove the child from the current position and then only append it to the new position.rahul– rahul2010年01月13日 05:56:50 +00:00Commented Jan 13, 2010 at 5:56
-
Thank you pulse, like I said I am inheriting this code but I will definitely make that change to prevent having unnecessary code. Thanks again!Jorge Israel Peña– Jorge Israel Peña2010年01月13日 05:58:30 +00:00Commented Jan 13, 2010 at 5:58
-
Ooh Ooh, read mine. I always recommend using JQuery for dom manipulation, or else you can't trust it'll work cross-browser.orokusaki– orokusaki2010年01月13日 06:02:12 +00:00Commented Jan 13, 2010 at 6:02
-
That's another reason why I was thinking about using it, but the consensus seems to be that it isn't necessary in this situation, perhaps it is too basic to leverage any of the advantages jQuery might have. Though the jQuery form definitely does look a lot neater.Jorge Israel Peña– Jorge Israel Peña2010年01月13日 06:07:57 +00:00Commented Jan 13, 2010 at 6:07
2 Answers 2
There's absolutely no need to use jQuery for this purpose. Assuming you do not already have a load event handler:
window.onload = function() {
// your code
};
Or throw it right before the end body tag, or to be more specific anywhere in the source after the submit button - there's nothing really dirty about it.
<script src="your-code.js"></script>
</body>
However, a quick jQuery rewrite..
$(function() {
$('#submit').appendTo('#btn-area').attr('tabIndex', 6);
if ( typeof yourVar != 'undefined' ) {
$('#textarea').val( yourVar );
}
$('#something').css('direction', 'ltr');
});
Did not test.
3 Comments
Here it is:
var sub_html = $('#submit').html();
$('#submit').html('');
$('#btn-area').html(sub_html);
$('#submit').attr('tabindex', 6);
if(typeof _some_var != 'undefined')
{
$('#some-textarea').val(_some_var);
}
$('#something').css('direction', 'ltr');