我如何添加SVG到我的Javascript .textContent?



我只是想在这里插入一个感叹号SVG,但我似乎做不到,我无法在谷歌上找到一个适当的答案。

SVG已下载,并包含在我的项目文件夹中。

if(email.validity.valueMissing) {
        emailError.textContent = '(SVG Here) You need to enter an e-mail address.';

假设e-mailError是html (span, p,div等)中的显示元素,则可以通过设置该元素的.innerHTML属性来加载图标和相关文本。

使用.textContent将导致显示标记文本而不是预期的布局(如您所发现的)

下面的工作片段演示了两者的区别。

const emailError=document.getElementsByClassName("emailError");
emailError[0].innerHTML = '<img src="https://stackoverflow.design/assets/img/logos/sf/sf-icon.svg" /> You need to enter an e-mail address.';
emailError[1].textContent = '<img src="https://stackoverflow.design/assets/img/logos/sf/sf-icon.svg" /> You need to enter an e-mail address.';
img {
width: 40px;
aspect-ratio: 1;
}
span {
border: 1px solid black;
display: flex;
align-items: center;
}
<p>Example loaded using .innerHTML:</p>
<p><span class="emailError"></span></p>
<p>Example loaded using .textContent:</p>
<p><span class="emailError"></span></p>

最新更新