SergSam SergSam - 5 months ago 19
jQuery Question

new to JQuery, dont know how to use local variables (with greasemonkey)

i was trying out to change a click event from a button with Greasemonkey,
while trying so i came across multiple problems and looked up some things online, but couldn't find any solution i understood or worked for me.

What i was going to try:
i tried to change a site, where it adds 2 elements when a button is pressed (i called the variable "but"),
but i want to remove the second element which it adds, so i overwrote the click event so it does add the 2 elements and right after it executes a function which removes the second element.

so bc iam new i not so sure how to get something from jquery and set it to a local javascript variable.

The problem code:

var but = $("#information");
but = but.children()[1];
but = but.find( "div" );
but = but.children[0];
but = but.find("a");
but = but.children[0];

$(but).click(function()
{
if(condition == 'true')
{
$.when(initialize()).then(deletehtml());
}
});
function deletehtml()
{
$($( "#content_box" ).children()[1]).remove();
}


Thank you for any help!

Answer

I don't know if it is your whole problem, but part of your problem is most likely from the use of [#]. That breaks a DOM Element out of the jQuery object and after that you cannot use jQuery methods against it unless you re-wrap $() it. Instead, use eq(#) to get the element if you want to keep using jQuery methods against it and to avoid having to re-wrap.

var $but = $("#information").children().eq(1);
$but = $but.find( "div" ).first();
$but = $but.find("a").first();

$but.on('click', function() {
    if (condition == 'true') {
        $.when(initialize()).then(deletehtml());
    }
});

function deletehtml() {
    $( "#content_box" ).children().eq(1).remove();
}