如何将选择器添加到元素HTML



我有一个span元素:

let infoButton = document.createElement("span"); 
infoButton.setAttribute("class", "info-point");

如何将选择器[bold]添加到元素中,以获得以下内容:

<span [bold] class="info-point"></span>

<span bold class="info-point"></span>

您可以使用以下指令制作粗体文本。

import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[boldText]'
})
export class BoldTextDirective {
constructor(el: ElementRef) {
el.nativeElement.style.fontWeight = 'bold';
}
}

HTML

<span boldText class="info-point"></span>

希望,这有帮助。

用空字符串设置属性应该会得到这样的结果。这被称为布尔属性(通常用于React、Angular等框架(。根据W3规范中的定义,它们是有效的。

let infoButton = document.createElement("span"); 
infoButton.setAttribute("class", "info-point");
infoButton.setAttribute("bold", "");
console.log(infoButton);

最好使用原生API来管理元素类。

var infoButton = document.createElement("span"); 
infoButton.classList.add("info-point");

最新更新