-1

I have a script from a JQuery Validation Engine. I want to set the prompt div before another div.

if($('#'+methods._getClassName(field.attr("id"))+'_msddHolder').length ){
var prompt = $('<div>');
$('#'+methods._getClassName(field.attr("id"))+'_msddHolder').before(prompt);
prompt.addClass(methods._getClassName(field.attr("id")) + "formError");
// add a class name to identify the parent form of the prompt
prompt.addClass("parentForm"+methods._getClassName(field.closest('form, .validationEngineContainer').attr("id")));
prompt.addClass("formError");

If I do it like this it won't work, if i manually set this:

$('#'+methods._getClassName(field.attr("id"))+'_msddHolder').before('<div>TEST</div>');

Then it works. Why?

Sparky
  • 98,165
  • 25
  • 199
  • 285
Simulator88
  • 617
  • 6
  • 12
  • 27
  • What exactly "won't work"? If you are not specific about your problem we have to guess, which has less chances to be of any help to you. – Felix Kling Feb 19 '13 at 10:20
  • 1
    The best thing you can do is create a http://www.jsfiddle.net/ demo which reproduces your problem. – Felix Kling Feb 19 '13 at 10:37

3 Answers3

0

You apply class after your before method. The class won't apply then on your element. Have you tried :

var prompt = $('<div><h4>I am a test</h4></div>');
$('#'+methods._getClassName(field.attr("id"))+'_msddHolder').before(prompt);

Just to see if you have an element insered ?

Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84
0

prompt isn't a pointer to your DOM element that you appended using before(), it is just a variable that contains an empty div, you need to apply its class before appending it to your document.

var prompt = $('<div>');
prompt.addClass("formError");
$('#'+methods._getClassName(field.attr("id"))+'_msddHolder').before(prompt);
StuR
  • 12,042
  • 9
  • 45
  • 66
  • What do you think jQuery is doing with the DOM element when it is inserted? Why would `prompt` not point to the inserted element anymore? – Felix Kling Feb 19 '13 at 10:24
  • You are all over this question aren't you, maybe try answering it? To answer your question, jQuery is adding a class to the div that is stored in the prompt var, and not to the div that was appended to the document using before(). – StuR Feb 19 '13 at 10:31
  • Yes, I'm trying to prevent incorrect answers. And I will answer the question once I have the information I need. So far I haven't. The element that `prompt` refers to is the same as the one that is inserted. jQuery does not create a copy (unless multiple elements are selected). Proof: http://jsfiddle.net/EJjdY/. – Felix Kling Feb 19 '13 at 10:35
0

Try this:

var prompt = $('<div>').text('test');
Jai
  • 74,255
  • 12
  • 74
  • 103