通过Javascript帮助解析另一个元素

时间:2010-09-09 19:11:59

标签: javascript dom

我想要替换下面的按钮有一个变量:

<script type="text/javascript">
  var btn = window.document.getElementById('btn_fb_1');
</script>
<button id="btn_fb_1" type="button">Log into Somewhere<br />(Joe Doe)</button>

使用上面的“btn”变量,如何用这样的文本替换整个元素(注意我需要保留“Joe Doe”:

Connected to Somewhere<br />(Joe Doe)

3 个答案:

答案 0 :(得分:1)

如果按钮包含在对象中,请更改父对象的innerHTML:

<span><button id="btn_fb_1" type="button">Log into Somewhere<br />(Joe Doe)</button></span>
<script type="text/javascript">
  var regEx = /\(([^)]*)\)/
  var btn = window.document.getElementById('btn_fb_1');
  btn.parentNode.innerHTML=btn.innerHTML.match(regEx)[1]; // extract joe doe (no error checking)
</script>

答案 1 :(得分:1)

试试这段代码:


var btn = window.document.getElementById('btn_fb_1');
var d = document.createElement('div');
var name = btn.innerHTML.match(/\(.*\)/);
d.innerHTML = 'Connected to Somewhere<br />'+name;
btn.parentNode.replaceChild(d, btn); // replace btn with d

答案 2 :(得分:0)

JavaScript框架使这更容易实现,但这应该可行。

btn.innerHTML = "Connected to Somewhere<br />(Joe Doe)";