views:

24

answers:

3

Hi there

i'm working on a ff-plugin which searchs a webpage for all textareas and places a warning before the submit button.

my code looks like this

var submitWarning = content.document.createElement("div");
submitWarning.innerHTML = "Fancy Message";
$('textarea', window.content.document).each(function() {
    var form = $(this, window.content.document).parents('form:first');
    $(form, window.content.document).children('input[type=submit]').each(function() {
         form.insertBefore(submitWarning, this);
    });
});

if i search all submits with $('input[type=submit]'.each... it works fine but since i added the thing with the textarea and the form:first i got problems (nothing happens)

p.s. i use the window.content.document thingy because its a ff-plugin and it won't work nothing without it

A: 

Try var form = $(this, window.content.document).closest('form');. Not sure if that's the ticket, but it's the first thing off my head.

Lance May
+1  A: 

You need to change it a bit, like this:

var submitWarning = content.document.createElement("div");
submitWarning.innerHTML = "Fancy Message";
$('textarea', window.content.document)
   .closest('form')
   .find('input[type=submit]')
   .before(submitWarning);

The argument syntax is $(selector, context), when finding the form, first there's .closest() which makes this easier, also when you have an element, you can just use $(this) inside it's .each(), no need to search for it again. Also, you can use .before() to make it easier :)

Nick Craver
and it works... thank you (didn't know the closest function
domueni
+1  A: 

The :has() selector is the best choice for me. Get rid of your extensive code and use this instead.

var buttons = $("form:has(textarea) input[type=submit]", window.content.document);
$("<div>").html("Fancy Message").insertBefore(buttons);
Seb
@Seb - Elegant. ;)
Lance May
Elegant, but expensive :) Also I'm not sure the document fragment creation style works inside of a FF plugin, If you need `window.content.document`, I would think `document.createDocumentFragment()` would need to be aliased as well, it isn't inside jQuery: http://github.com/jquery/jquery/blob/master/src/manipulation.js#L415
Nick Craver
Why expensive? If you're about to answer 'because of the *:has* selector, do you actually *know* how it works? :)
Seb
@Seb - Yes I know how it works, keep in mind you're doing a tree search twice, instead of a `getElementsByTagName`, parent climb then tree search, which is faster. `:has(selector)` is just a wrapper for `!!$(selector, context).length`
Nick Craver