简体   繁体   English

如何在 JavaScript 中为创建的元素添加 ID?

[英]How to add an ID onto a created element in JavaScript?

My original question was marked falsely by another user as a duplicate but the link provided did not answer any parts of the question asked so I will ask another.我原来的问题被另一个用户错误地标记为重复,但提供的链接没有回答问题的任何部分,所以我会问另一个。 Making the site builder I ran into an issue where the prompt value when pressing okay is not used as the text in the created h1 .制作站点构建器我遇到了一个问题,即按下 OK 时的提示值未用作创建的h1的文本。 Why is this?为什么是这样? The class applies and creates all the elements I wanted to but the text is not present on the site at all, and there are no errors in the code because it all works fine.该类应用并创建了我想要的所有元素,但网站上根本不存在文本,并且代码中没有错误,因为一切正常。

 .new-hd { position: fixed; z-index: 5; bottom: 0; right: 0; } .new-para { position: fixed; z-index: 5; bottom: 0; left: 0; } .classic-hd { max-width: 100vw; width: 100vw; max-height: 15vh; height: 15vh; position: absolute; left: 0; top: 0; background-color: black; display: flex; align-items: center; } #classic-hd-txt { color: white; font-family: sans-serif; text-indent: 3vw; } .fa-times { color: white; position: absolute; top: 0.25vh; right: 1vw; z-index: 5; }
 <!DOCTYPE html> <html> <head> <title>Make a Site</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css"> </head> <body> <button type="button" class="new-hd"> Make Header </button> <button type="button" class="new-para"> Make Paragraph </button> <script> $(document).ready(function() { $(".new-hd").click(function() { var newHdTxt = window.prompt("What would you like your Header Text to be?", "Enter Response Here"); var newHdCont = document.createElement("header"); var newHd = document.createElement("h1"); $(newHdCont).addClass("classic-hd"); $(newHd).addClass("classic-hd-txt"); document.getElementsByClassName("classic-hd-txt").innerHTML = newHdTxt; document.body.appendChild(newHdCont); newHdCont.appendChild(newHd); //alert(newTxt); }); $(".new-para").click(function() { document.createElement("p"); }); }); </script> </body> </html>

On behalf of Nik who gave the answer, here is the way you resolve this.代表给出答案的 Nik,这是您解决此问题的方法。 Instead of using the DOM selector get.ElementsByClassName().innerHTML use the method newHd.innerText = newHdTxt .而不是使用 DOM 选择器get.ElementsByClassName().innerHTML使用方法newHd.innerText = newHdTxt

使用 attr 函数添加 id 属性。像这样

$jqueryElement.attr('id', 'change_it_to_what_you_want_but_should_be_unique');

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

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