在chrome扩展的工具提示中创建html元素



我想使用javascript创建一个HTML元素(div(,并将其用作工具提示。我可以通过以下操作创建简单的元素:

const element = document.createElement("div");
element.id = "myID"

这很好。。。但是,我想在工具提示中添加一个表(和一些其他HTML(,所以我试图进行

element.appendChild(childElement); //where the childElement is another document.createElement("") that contains all the HTML I want.

或:

element.insertAdjacentHTML('afterbegin', '<table></table>');

然而,什么也没发生。没有错误,但它也不会附加它。我是不是错过了什么?

如果重要的话,这发生在我正在建造的铬扩建的contentScripts.js内部。

编辑

div创建的完整代码:

const element = document.createElement("div");
element.id = "tooltip-creation";
element.classList.add("tooltip");
const childElement = document.createElement("div");
childElement.id = "data";

//I've attempted to do .appendChild, innerHTML, and .insertAdjacentHTML (as can be seen here) and neither works but no error is given.
element.appendChild(childElement);

element.insertAdjacentHTML('afterbegin','<table border="1"><tr><td><strong>OMG</strong></td></tr></table>');
element.innerHTML = "<table border="1"><tr><td><strong>OMG</strong></td></tr></table>";

另外,我有两个功能:

document.addEventListener("mouseover", function(e){
if (e.target.classList.contains("tooltip")) {
createTooltip(e);
}
});
document.addEventListener("mouseout", function(e){
if (e.target.classList.contains("tooltip")) {
removeAllTooltips();
}
});

我认为您的问题是实际上没有将工具提示附加到任何东西上。您需要将element附加到DOM中已经存在的节点。这是我从您的代码中得到的一个工作示例(没有任何CSS(,唯一的区别是我将element节点附加到了DOM中一个名为root的现有元素上。

https://jsfiddle.net/irantwomiles/09o7vuj5/12/

最新更新