简体   繁体   English

为什么我得到 [object HTMLParagraphElement]

[英]Why did I get [object HTMLParagraphElement]

I am a newbie.我是新手。 Here is my code:这是我的代码:

<html>
  <head>
    <script type="text/javascript">
      function replyOne () {
        document.getElementById("comment_content").value = document.getElementById("username")
      }
    </script>
  </head>
  <body>
    <p id="username">Jack</p>
    <textarea id="comment_content" ></textarea>
    <button onclick="replyOne()">Copy Text</button>
  </body>
</html>

I expect that when I click the button, it will copy 'Jack' to the textarea.我希望当我单击该按钮时,它会将“Jack”复制到文本区域。 But instead it just writes '[object HTMLParagraphElement]'.但它只是写入“[object HTMLParagraphElement]”。

It should be:它应该是:

document.getElementById("comment_content").value =
    document.getElementById("username").innerHTML

Without the .innerHTML , it will try to copy in the actual element, not its content.如果没有.innerHTML ,它将尝试复制实际元素,而不是其内容。

You can use textContent,innertext,innerHTML.But two of them are browser specific and innerHTML can work on three major browser.您可以使用 textContent、innertext、innerHTML。但其中两个是特定于浏览器的,innerHTML 可以在三个主要浏览器上工作。

Also you can parse the dom by parent children combination and will get required value.您也可以通过父子组合解析 dom 并获得所需的值。

 function replyOne () {
    document.getElementById("comment_content").value=document.getElementById("username").innerHTML;

    //OR 
    document.getElementById("comment_content").value=document.getElementById("username").textContent;

    }

I am a retired civil engineer.我是一名退休的土木工程师。 I'm 71, and I'm sorry that I have to be the last of the programmers to give you the solution!我今年 71 岁,很抱歉我不得不成为最后一个为您提供解决方案的程序员! You need to extract what you are looking for using the obj.innerText attribute and you will solve the problem-:您需要使用obj.innerText属性提取您正在寻找的内容,您将解决问题 - :

var t= document.getElementById("comment_content");
var text=t.innerText;
alert(t);

This is solution of [objectHTMLParagraphElement] with example这是 [objectHTMLParagraphElement] 示例的解决方案

var sel = document.getElementById('ex').innerHTML; // without innerHTML this will 
comes [objectHTMLParagraphElement]
var txt = sel + "Hello";    
document.write(txt); // output Hello

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM