简体   繁体   English

删除JavaScript中的所有标签元素

[英]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 ). 在我的应用程序中,我检查用户的浏览器是否支持HTML5,并能够在输入字段中显示占位符 (使用Modernizr )。 If so, I want to remove all labels from the HTML document in an automatized way, but I really don't know how. 如果是这样,我想以一种自动化的方式从HTML文档中删除所有labels ,但是我真的不知道如何。

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. 到目前为止,我已将id分配给标签并逐个删除了标签,但我想使用一种更有效的方法。

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. 对于具有ID的那些ID,请查找并删除相关标签。

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!! 无需jQuery !! (because it is actually possible to do stuff in raw JS...) (因为实际上可以在原始JS中做一些事情...)

If you are OK with using jQuery, this is an one-liner: 如果您可以使用jQuery,那么这是一种方法:

$('label').remove();

Example here - uncomment the one line in the JavaScript part to see the effect: 此处的示例-取消注释JavaScript部分中的一行以查看效果:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM