简体   繁体   English

通过javascript在文本区域顶部添加标题

[英]Add header on top of text area via javascript

I have this sample code:我有这个示例代码:

 window.addEventListener('load', () => { // sticky profile notes const notes = document.querySelector('#id_notes'); // Get textarea element const headerDiv = document.createElement("div"); // Create a <div> element headerDiv.innerHTML = "SHOULD BE ON TOP"; // Insert instructions // add header on top notes.prepend(headerDiv); });
 <body> <textarea id="id_notes" style="background-color: #ffffcc;"> </textarea> </body>

in which I plan to add a header the same size as the textarea.其中我计划添加一个与 textarea 大小相同的标题。 but instead of it being added on top of the textarea, its being added inside it.但不是将其添加到 textarea 顶部,而是将其添加到其中。

在此处输入图片说明 I can only use JS because I don't know how to add it on a Django template.我只能使用 JS,因为我不知道如何将它添加到 Django 模板上。 Thanks in advance!提前致谢!

EDIT : added desired end result:编辑:添加所需的最终结果:

在此处输入图片说明

You can use Node#insertBefore :您可以使用Node#insertBefore

 window.addEventListener('load', () => { // sticky profile notes const notes = document.querySelector('#id_notes'); // Get textarea element const headerDiv = document.createElement("div"); // Create a <div> element headerDiv.innerHTML = "SHOULD BE ON TOP"; // Insert instructions // add header on top notes.parentNode.insertBefore(headerDiv, notes); });
 <textarea id="id_notes" style="background-color: #ffffcc;"></textarea>

Use insertBefore() instead使用insertBefore()代替

 window.addEventListener('load', () => { const notes = document.querySelector('#id_notes'); // Get textarea element const headerDiv = document.createElement("div"); // Create a <div> element headerDiv.innerHTML = "SHOULD BE ON TOP"; // Insert instructions // add header on top notes.parentNode.insertBefore(headerDiv, notes) });
 <body> <textarea id="id_notes" style="background-color: #ffffcc;"> </textarea> </body>

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

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