views:

37

answers:

2

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!

+3  A: 

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.

meder
I already fixed the problem mentioned in the post by putting this in the footer, I just figured it would make more sense to have this code as jQuery, but I guess that is not necessary then.
Jorge Israel Peña
So I'm guessing using jQuery in this situation would only add unnecessary overhead, I won't use it then. Thanks for the conversion, regardless.
Jorge Israel Peña
Pretty much, and would be inconsistent with all the rest of your DOM Scripting if you have lots of scripts.
meder
+1  A: 

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');
orokusaki