删除字符串的一部分(Javascript)

时间:2015-08-31 20:25:09

标签: javascript

如果按下按钮,我试图删除部分文字。

所以我做了什么:

<div "topbar">
    hey there! <div class="close" id="topbar_search_close">remove this button</div>
</div>

和javascript:

document.getElementById("topbar").innerHTML -= '<div class="close" id="topbar_search_close">&times;</div><div class="search_main">';

还有其他选择吗?谢谢!

2 个答案:

答案 0 :(得分:0)

这应该从元素中删除所有子节点。

document.getElementById("topbar").empty();

如果您只想更改文字,并且知道文字是什么。

document.getElementById("topbar").text = "some new text";

如果它有所不同,那么请更具体地说明你想要的东西。

答案 1 :(得分:0)

要删除部分字符串,您可以使用String.prototype.replace,如下所示:

&#13;
&#13;
window.onload = function() {
  document.getElementById('topbar_search_close').addEventListener('click', function(e) {
    var topbar = document.getElementById('topbar');
    topbar.innerHTML = topbar.innerHTML.replace('<div class="close" id="topbar_search_close">remove this button</div>', '');
  });
}
&#13;
<div id="topbar">
  hey there!
  <div class="close" id="topbar_search_close">remove this button</div>
</div>
&#13;
&#13;
&#13;

但删除DOM节点是一个坏主意。您可以像这样删除它:

&#13;
&#13;
window.onload = function() {
  document.getElementById('topbar_search_close').addEventListener('click', function(e) {
    var node = e.target; //topbar_search_close
    node.parentNode.removeChild(node);
  });
}
&#13;
<div id="topbar">
  hey there!
  <div class="close" id="topbar_search_close">remove this button</div>
</div>
&#13;
&#13;
&#13;