最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

getElementByID in javascript [object HTMLSpanElement] - Stack Overflow

programmeradmin1浏览0评论

I have the following problem... i want to replace a text of a div with an other text of a span.

So I tried this:

<main>
  <span id="export_text">This text should be exported</span><br>
  <div id="import_text">Here the new text should be after pressing the button</div><hr>
  <a onclick="run()"><button>run</button></a>
</main>

<script type="text/javascript">
  function run() {
    document.getElementById('import_text').innerHTML = document.getElementById('export_text');
  }
</script>

now if i press the button the text in the div gets replaced with [object HTMLSpanElement] instead of the text from the span. What did i do wrong here?

Thank you!

I have the following problem... i want to replace a text of a div with an other text of a span.

So I tried this:

<main>
  <span id="export_text">This text should be exported</span><br>
  <div id="import_text">Here the new text should be after pressing the button</div><hr>
  <a onclick="run()"><button>run</button></a>
</main>

<script type="text/javascript">
  function run() {
    document.getElementById('import_text').innerHTML = document.getElementById('export_text');
  }
</script>

now if i press the button the text in the div gets replaced with [object HTMLSpanElement] instead of the text from the span. What did i do wrong here?

Thank you!

Share Improve this question asked Jul 3, 2015 at 10:06 look002look002 131 silver badge2 bronze badges 3
  • You forgot to put innerHTML onto the end of the export_text element – CodingIntrigue Commented Jul 3, 2015 at 10:08
  • Change to document.getElementById('export_text').innerHTML, don't just assign that element. – fuyushimoya Commented Jul 3, 2015 at 10:08
  • im still getting the same – look002 Commented Jul 3, 2015 at 10:10
Add a ment  | 

1 Answer 1

Reset to default 4

Justt add .innerHTML at the end of your export text selector:

function run() {
    document.getElementById('import_text').innerHTML = document.getElementById('export_text').innerHTML;
}

I also strongly suggest you to move your event in JS:

document.getElementById("myBtn").addEventListener("click", run);

Updated HTML:

<main> <span id="export_text">This text should be exported</span>
    <br>
    <div id="import_text">Here the new text should be after pressing the button</div>
    <hr> <a><button id="myBtn">run</button></a>
</main>

JSFiddle: http://jsfiddle/ghorg12110/n4cwem28/1/

发布评论

评论列表(0)

  1. 暂无评论