I have the following HTML:
<div class="control-group">
<label class="control-label-sub">Description/Pack Size</label>
<div class="controls">
<input type="text" name="packetSize" class="wfinput required form_error" id="packetSize" />
<label id="packetSize-error" class="form_error" for="packetSize">
This field is required.
</label>
</div>
</div>
Is there a way to select the <label>
element that is the child of .control-group
(ie, the one with "Description/Pack Size" text), from the <input />
text field in my HTML?
To select the <label>
element that is above the <input/>
element, you could:
.closest()
to select the first .control-group
above the <input/>
element and then .control-group
This can be achieved via the following jQuery script:
const input = $('input[name="packetSize"]');
const controlGroup = input.closest('.control-group');
const label = $('label', controlGroup);
It's possible to condense this into a single line but I've broken it into steps for clarity. Hope that helps.
If you want to get all label that class was named "control-label-sub".
var element = $("label.control-label-sub")
And If you want to get only that label I prefer following
var element = $("input#packetSize").parent().prev()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.