Reputation: 12341
In my application, I check if the user's browser is HTML5-capable and is able to display placeholders in input fields (using Modernizr). If so, I want to remove all labels
from the HTML document in an automatized way, but I really don't know how.
In layman terms, if the user's browser supports placeholders I'd like to turn this:
<label for="email">
Email:
</label>
<input type="email" id="email" placeholder="Your email">
Into this -in every occurrence-:
<input type="email" id="email" placeholder="Your email">
All I have is:
if (Modernizr.input.placeholder) {
// Remove all labels from the HTML document
}
Until now I assigned id
s to the labels and removed them one by one, but I'd like a more efficient way to do it.
Upvotes: 0
Views: 9316
Reputation: 263
Couldn't find any relevant questions for me to post this answer that might help. If someone is looking to remove a label for specific, via jquery:
<label for="billing_wooccm15" class="">Snacks <abbr class="required" title="required">*</abbr></label>
$('label[for="billing_wooccm14"]').css({
'margin-top': '-15px',
'padding' : '0'
});
Upvotes: 0
Reputation: 324760
First, build a table of the existing labels like so:
var labels = {}, tags = document.getElementsByTagName('label'), l = tags.length, i;
for( i=0; i<l; i++) labels[tags[i].getAttribute("for")] = tags[i];
Next, find input elements that have placeholders. For those that do, and have IDs, look for and remove the relevant label.
tags = document.getElementsByTagName('input');
l = tags.length;
var lb;
for( i=0; i<l; i++) {
if( !tags[i].getAttribute("placeholder")) continue;
if( lb = labels[tags[i].id]) lb.parentNode.removeChild(lb);
}
Done! No jQuery required!! (because it is actually possible to do stuff in raw JS...)
Upvotes: 6
Reputation: 28618
If you are OK with using jQuery, this is an one-liner:
$('label').remove();
Example here - uncomment the one line in the JavaScript part to see the effect:
Upvotes: 2