首先,
document.querySelector("#elem");
与 document.getElementId 不同,它有一个优势,它可以返回类。但是,由于它只返回具有该类名的第一个对象,因此它的实用性大大降低,因此如果您不是专门寻找具有该类名的第一个对象,则最好只使用一个 id。如果你使用,
document.querySelectorAll
但是,我相信(我可能错了),它将具有该类名的所有项目作为数组返回,其中常规 querySelector 等效于 querySelectorAll[0]。另一个优点是您可以通过它运行 css3 查询,这非常有用。
第二,
document.getElementById("elem");
与 queryselector 相比有一个非常好的优势,因为它快了将近5 倍,所以如果你坐在那里有几千行代码并且你想优化所述代码,那么 getElementById 是要走的路。
Lastly,
document.querySelector("[id=elem]");
I, personally, don't see the need to use this in any situation. If you needed a querySelector, why not just use a # ? This is exactly equivalent to your first example of querySelector, however it has a lot of useless charaters.
Edit: Just to be clear, in summary, you're probably better off using document.getElementById.