So the html looks like this
<div class="col-12">
<label>Enter your post code <span class="text-danger">*</span> </label>
<input type="text" class="form-control" id="form_zipbox" name="custom[map-zip]" value="" autocomplete="off">
</div>
And I am trying to access the label and replace the text.
The col-12 selector is not unique, so I have been trying to target the input with the id.
I've tried the following
e = document.getElementById("form_zipbox");
e.closest("label"); // returns null
e.closet("div > childElement"); // null. As does child, childNode, just for sake of trying.
How can I access the label.
e.closest("div"); // Does return col-12 obviously
Just can't get a hold of this label. Can anyone please point me in the right direction. Btw, it needs to be vanilla js, not jquery. Thanks
Any help is much appreciated.
You can use firstElementChild using closest('div')
to get the label only. Using pure JavaScript
let e = document.getElementById("form_zipbox"); let div = e.closest("div").firstElementChild; console.log(div)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <div class="col-12"> <label>Enter your post code <span class="text-danger">*</span> </label> <input type="text" class="form-control" id="form_zipbox" name="custom[map-zip]" value="" autocomplete="off"> </div>
You can also target directly at the label using previousElementSibling of the input.
let e = document.getElementById("form_zipbox"); console.log(e.previousElementSibling)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <div class="col-12"> <label>Enter your post code <span class="text-danger">*</span> </label> <input type="text" class="form-control" id="form_zipbox" name="custom[map-zip]" value="" autocomplete="off"> </div>
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.