how to clear a span inside a div

喜你入骨 提交于 2019-12-11 06:54:07

问题


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

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 spans or the content of all the spans.


回答1:


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

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



回答2:


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

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

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




回答3:


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

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



回答4:


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

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



来源:https://stackoverflow.com/questions/12633683/how-to-clear-a-span-inside-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!