Thanks for the quick response.
I had a look at the wrap() function but couldn't see that it would work for a complex structure that I want to pass it, as can be seen in the templatesHTML below. If it is possible, then I certainly would love to use it.
Still, this doesn't change the problem that I think I've found. Here's a refactored peice of code that should highlight the error better:
- var templatesHTML = '';
- templatesHTML += '<div id="templates">';
- templatesHTML += ' <div id="_someTemplate">';
- templatesHTML += ' <div>';
- templatesHTML += ' <div id="content"></div>';
- templatesHTML += ' </div>';
- templatesHTML += ' </div>';
- templatesHTML += ' <div id="_anotherTemplate">';
- templatesHTML += ' <div>';
- templatesHTML += ' <div id="content"></div>';
- templatesHTML += ' </div>';
templatesHTML += ' </div>'; - templatesHTML += '</div>';
- function wrap(clazz) {
- $('.'+clazz).each(function () {
- // get the template and replace the content holder with a copy
of the actual content
- var templatedContent = templates[clazz].clone();
- var content = $(this).clone();
- templatedContent.find('#content').replaceWith(content);
- // now that we have the new wrapped content, replace the
existing content
- (this.id != ''?$('#' +
this.id):$(this)).replaceWith(templatedContent);
- });
- };
- var templates = {};
- $(document).ready(function() {
- // build templates dictionary and wrap the elements
- var templateWrappers = $(templatesHTML).children();
- for (i=0; i < templateWrappers.length; i++) {
- templateWrapper = templateWrappers[i];
- templates[templateWrapper.id] = $(templateWrapper).children();
- wrap(templateWrapper.id);
- }
- });
And the HTML looks like this:
- <form action="/Account/Logon" method="post">
- <fieldset>
- <legend>Logon</legend>
- <div class="formFeildsContainer">
<div id="usernameFormRow" class="formRow"> - <div class="labelWrapper">
- <label for="username">YOUR USERNAME:</label>
- </div>
- <div class="fieldWrapper">
- <input MaxLength="25" class="_input _border" id="username" name="username" type="text" value="" />
- </div>
- </div>
- <div id="passwordFormRow" class="formRow">
- <div class="labelWrapper">
- <label for="password">YOUR PASSWORD:</label>
- </div>
- <div class="fieldWrapper">
- <input MaxLength="15" class="_input _border" id="password" name="password" type="password" />
- </div>
- </div>
- <div class="formRow">
- <div class="labelWrapper"></div>
- <div class="fieldWrapper">
- <a href="/Account/ForgotPassword" id="forgotPasswordLink">FORGOTTEN YOUR LOGIN DETAILS?</a>
- </div>
- </div>
- </div>
- <div id="submitFormRow" class="formRow">
- <input type="submit" value="SIGN IN"/>
- </div>
- </fieldset>
- </form>
After digging in a bit further, it seems that it only happens for input fields and replaceWith doesn't work when finding those feilds as part of the class selector, but it does when using an id selector.
NOTE: I've simplified the structure of the templates significanlty to demonstrate the problem