Javascript 如何清除div内的跨度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12633683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:54:31  来源:igfitidea点击:

how to clear a span inside a div

javascriptjqueryhtmlclear

提问by telexper

I want to clear a value of a span inside a div without deleteing other contents only the contents of a span.

我想清除 div 内的跨度值而不删除其他内容,只删除跨度的内容。

ex: body:

例如:身体:

<div id="content">
  <span>one</span>

  <input type="text" />
  <input type="text" />

  <span>two</span>
  <span>three</span>

  <select>
        <option selected="selected" value=""></option>
        <option value="Monday">Monday</option>
        <option value="Tuesday">Tuesday</option>
        <option value="Wednesday">Wednesday</option>
        <option value="Thursday">Thursday</option>
        <option value="Friday">Friday</option>
        <option value="Saturday">Saturday</option>
        <option value="Sunday">Sunday</option>
  </select>
</div>

script:

脚本:

<script type="text/javascript">
function restSel() {
   document.getElementById("#content span").innerHTML="";
};
</script>

Clear all the spansor the content of all the spans.

清除所有spans或 的所有内容spans

回答by digidigo

If you were using JQuery ( which will bring you much joy ), then you could do it like this.

如果您正在使用 JQuery(这会给您带来很多乐趣),那么您可以这样做。

$("span").html("");

回答by Passerby

If you're only using pure JS, you can try this:

如果你只使用纯 JS,你可以试试这个:

document.getElementById("content").getElementsByTagName("span")[0].innerHTML="";

You can replace 0to any valid index to clear certain span.

您可以替换0为任何有效索引以清除某些span.

回答by Daedalus

Alright, I lied I guess. This is more simpler than I thought, thanks to @Passerby;

好吧,我猜我撒了谎。感谢@Passerby,这比我想象的要简单;

for (i = 0; i < document.getElementById('content').getElementsByTagName('span').length; i++) {
    document.getElementById('content').getElementsByTagName('span')[i].innerHTML = '';
}

回答by RRikesh

Using jQuery: To target only the spanthat are in your div with id = "content"(in case you have other spansin your document:

使用 jQuery:仅针对id = "content" 的div 中的跨度(以防您的文档中有其他跨度

$('div#content').find('span').html('');

$('div#content').find('span').html('');