在ID值为section_form_id
:的div之后,我有一点JS可以向页面添加电子邮件超链接
// build email
var elmNewContentCustomer = document.createElement('a');
var elmFoo = document.getElementById('section_form_id');
elmNewContentCustomer.href = 'mailto:me@example.com?subject=Something';
elmNewContentCustomer.setAttribute("style", "color:blue;");
elmNewContentCustomer.setAttribute("id", "email_customer_id");
elmNewContentCustomer.appendChild(document.createTextNode('Email Customer'));
elmFoo.parentNode.insertBefore(elmNewContentCustomer, elmFoo.nextSibling);
这很好用。然而,我想把超链接放在DIV中,所以我设置了DIV的样式属性
我尝试使用这种方法,即创建一个DIV,并使用appendChild
将其插入电子邮件块之前,但它不起作用:
var elmNewEmailDev = document.createElement('div');
var elmFoo2 = document.getElementById('email_customer_id');
elmNewEmailDev.setAttribute("style", "background:yellow;");
elmNewEmailDev.appendChild(elmFoo.parentNode.insertBefore(elmNewContentCustomer, elmFoo.nextSibling));
elmFoo2.parentNode.insertBefore(elmNewEmailDev, elmFoo.elmFoo2);
如何将DIV包裹在超链接周围,以便使用setAttribute
来控制该DIV的样式?
根据需要使用此方法获取结果。
var myEmailLink = "<a href='mailto:a@b.com'>a@b.com</a>";
var myDiv = document.getElementById("section_form_id");
myDiv.insertAdjacentHTML('afterEnd', myEmailLink )
<div id="section_form_id">
My Div Here
</div>