使用 typescript 如何创建 html 元素——迹忆客-ag捕鱼王app官网
要在 typescript 中创建 html 元素:
- 使用
document.createelement()
方法创建元素。 - 在创建的元素上设置任何属性或内部 html。
- 使用 appendchild() 方法将元素添加到页面。
这是本文中示例的 html。
这是相关的 typescript 代码。
const el = document.createelement('div');
// 将文本内容添加到元素
el.textcontent = 'hello world';
// 或者设置元素的innerhtml
// el.innerhtml = `hello world`;
// (可选)在元素上设置属性
el.setattribute('title', 'my-title');
// (可选)在元素上设置样式
// el.style.backgroundcolor = 'salmon';
// el.style.color = 'white';
// 将元素添加到 dom
const box = document.getelementbyid('box');
box?.appendchild(el);
我们使用 document.createelement
方法来创建元素。
我们传递给该方法的唯一参数是要创建的元素的类型(示例中为 div)。
createelement
方法返回新创建的元素。
我们可以使用 textcontent
属性设置元素的文本内容或使用 innerhtml
属性设置元素的内部 html 标记。
这是一个设置元素内部 html 的示例。
const el = document.createelement('div');
el.innerhtml = `
hello world
`;
// (可选)在元素上设置属性
el.setattribute('title', 'my-title');
// (可选)在元素上设置样式
// el.style.backgroundcolor = 'salmon';
// el.style.color = 'white';
// 将元素添加到 dom
const box = document.getelementbyid('box');
box?.appendchild(el);
我使用反引号 ``(不是单引号)来包装 html 字符串,因为反引号允许我们轻松创建多行字符串。
我们不应该将 innerhtml 属性与用户提供的数据一起使用而不对其进行转义。 这将使我们的应用程序容易受到跨站点脚本攻击。
如果需要在元素上设置属性,需要使用 setattribute
方法。
setattribute 方法有 2 个参数:
- name - 要设置其值的属性的名称。
- value - 分配给属性的值。
在示例中,我们将元素的 title 属性的值设置为 my-title。
const el = document.createelement('div');
el.innerhtml = `
hello world
`;
el.setattribute('title', 'my-title');
// 将元素添加到 dom
const box = document.getelementbyid('box');
box?.appendchild(el);
如果属性已存在,则更新值,否则添加具有指定名称和值的新属性。
我们可以通过在其样式对象上设置属性来设置元素的样式。
const el = document.createelement('div');
el.innerhtml = `
hello world
`;
el.style.backgroundcolor = 'salmon';
el.style.color = 'white';
// 将元素添加到 dom
const box = document.getelementbyid('box');
box?.appendchild(el);
注意
,使用 style 对象时,多词属性是驼峰式大小写的。
我们可以使用 appendchild
方法将元素添加到页面。
该方法将一个节点添加到调用它的元素的子元素列表的末尾。
注意
,我们在访问 appendchild 方法之前使用了可选链接 (?.) 运算符。
如果引用为空(null
或 undefined
),则可选链接 (?.)
运算符会短路。
换句话说,如果 box 变量存储了一个 null 值,我们不会尝试在 null 上调用 appendchild 方法并获得运行时错误。
box 变量可能为 null,因为如果 document.getelementbyid()
方法没有找到具有提供的 id 的元素,它会返回 null。