简体   繁体   English

使用 JavaScript 更改表单中 h1 元素的值

[英]Change the Value of h1 Element within a Form with JavaScript

I have two forms on an HTML5 page.我在 HTML5 页面上有两个表单。 Each form has a name and an id.每个表单都有一个名称和一个 ID。 The second form has an h1 element, which also has a name and an id.第二种形式有一个 h1 元素,它也有一个名称和一个 ID。 How do I change the text of this h1 element on the second form using plain JavaScript?如何使用纯 JavaScript 在第二个表单上更改此 h1 元素的文本?

尝试:


document.getElementById("yourH1_element_Id").innerHTML = "yourTextHere";

你可以使用这个: document.getElementById('h1_id').innerHTML = 'the new text';

document.getElementById("myh1id").innerHTML = "my text"

您可以尝试以下方法:

document.getElementById("your_h1_id").innerHTML = "your new text here"

你也可以使用这个

document.querySelector('yourId').innerHTML = 'Content';

You can do it with regular JavaScript this way:您可以通过以下方式使用常规 JavaScript 执行此操作:

document.getElementById('h1_id').innerHTML = 'h1 content here';

Here is the doc for getElementById and the innerHTML property .这是getElementByIdinnerHTML 属性的文档。

The innerHTML property description: innerHTML属性说明:

A DOMString containing the HTML serialization of the element's descendants.包含元素后代的 HTML 序列化的 DOMString。 Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.设置 innerHTML 的值会删除元素的所有后代,并用通过解析字符串 htmlString 中给出的 HTML 构造的节点替换它们。

You should use the textContent property as a best practice.您应该使用textContent属性作为最佳实践。 The innerHTML property changes everything inbetween the h1 tags, which could mean that if there was something else between the h1 tags, like an emphasis or strong tag it would disappear. innerHTML属性会更改h1标签之间的所有内容,这可能意味着如果h1标签之间存在其他内容,例如强调或强标签,它将消失。 textContent would only change the text of the header. textContent只会更改标题的文本。 It's probably not a big deal for your h1 but it may make a difference knowing the difference in the future.这对你的h1来说可能没什么大不了的,但知道未来的不同可能会有所不同。

document.getElementById('h1_id').textContent = 'h1 content';

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

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