javascripthtmlmodernizr

Remove all label elements in JavaScript


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 ids to the labels and removed them one by one, but I'd like a more efficient way to do it.


Solution

  • 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: