I'm trying to wrap <label>
, <input type="text" />
, and <select>
elements with <div class="formItem"></div>
to fix some positioning on a form that I can't directly edit. For some reason, when I try to use the following code:
$("label").before("<div class=\"formItem\">");
$("input[type=text]").after("</div>");
$("select").after("</div>");
It doesn't work. It just adds <div class="formItem"></div>
before every <label>
which doesn't help me.
I've taken a look at .wrap();
but it isn't clear how I can use that to wrap multiple elements like I'm trying to do. Here's an example of the HTML markup:
<label>Text Box</label>
<input type="text" name="Text Box" />
<label>Select Menu</label>
<select name="Select Menu">
<option>Example</option>
</select>
There's about 10 sets, 9 text boxes, and 1 select box if that matters.
jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector).
You can use the . wrapAll() method.
WRAP stands for Widen Your Options, Reality-Test Your Assumptions, Attain Distance Before Deciding, and Prepare to Be Wrong. Widen Your Frame. One of the main pitfalls in decision making is having a narrow frame. That means you don't consider possible alternatives that might be better options.
The wrap() method wraps specified HTML element(s) around each selected element.
That's just not how the jQuery API works. At all.
.before()
:
Insert content, specified by the parameter, before each element in the set of matched elements.
.after()
:
Insert content, specified by the parameter, after each element in the set of matched elements.
Don't think in terms of open- and close-tags. Think in terms of actual elements.
You are probably looking for .wrapAll()
.
$('label').each(function () {
$(this).next('input, select').andSelf().wrapAll('<div class="formItem"/>');
});
With jquery, you can only add complete elements. That is, they must include the end tags. This is because what you are really doing is calling document.createElement('div')
. So to solve this problem, keeping as close to the original code as possible, just use:
var newEl = $("select").after("<div class=\"formItem\"></div>");
$("input[type=text]").appendTo(newEl);
$("select").appendTo(newEl);
Try this:
$('label').next().andSelf().wrap("<div class=\"formItem\">");
It will enclose label elements plus its following sibling in a div.formItem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With