jsÔõô»ñÈ¡ÔªËØ
ͨ¹ýjavascript»ñÈ¡ÔªËصÄÒªÁì°üÀ¨£ºÊ¹ÓÃgetelementbyid()ͨ¹ýidÊôÐÔ»ñÈ¡ÔªËØ¡£Ê¹ÓÃgetelementsbytagname()ͨ¹ý±êÊðÃû»ñÈ¡Æ¥ÅäÔªËØÜöÝÍ¡£Ê¹ÓÃgetelementsbyclassname()ͨ¹ýÀàÃû»ñÈ¡Æ¥ÅäÔªËØÜöÝÍ¡£Ê¹ÓÃqueryselector()ʹÓÃcssÑ¡ÔñÆ÷»ñÈ¡µÚÒ»¸öÆ¥ÅäÔªËØ¡£Ê¹ÓÃqueryselectorall()ʹÓÃcssÑ¡ÔñÆ÷»ñÈ¡ËùÓÐÆ¥ÅäÔªËØÜöÝÍ¡£
ÔõÑùʹÓà JavaScript »ñÈ¡ÔªËØ
ҪʹÓà JavaScript »ñÈ¡ HTML ÔªËØ£¬¿ÉÒÔʹÓÃÒÔÏÂÒªÁ죺
1. getElementById()
ͨ¹ýÔªËØµÄ id ÊôÐÔ»ñÈ¡ÔªËØ¡£
const element = document.getElementById("myElement");
µÇ¼ºó¸´ÖÆ
2. getElementsByTagName()
ͨ¹ý±êÊðÃû³Æ»ñÈ¡ËùÓÐÆ¥ÅäÔªËصÄÜöÝÍ¡£
const elements = document.getElementsByTagName("p");
µÇ¼ºó¸´ÖÆ
3. getElementsByClassName()
ͨ¹ýÀàÃû»ñÈ¡ËùÓÐÆ¥ÅäÔªËصÄÜöÝÍ¡£
const elements = document.getElementsByClassName("myClass");
µÇ¼ºó¸´ÖÆ
4. querySelector()
ʹÓà CSS Ñ¡ÔñÆ÷»ñÈ¡µÚÒ»¸öÆ¥ÅäµÄÔªËØ¡£
const element = document.querySelector("#myElement");
µÇ¼ºó¸´ÖÆ
5. querySelectorAll()
ʹÓà CSS Ñ¡ÔñÆ÷»ñÈ¡ËùÓÐÆ¥ÅäÔªËصÄÜöÝÍ¡£
const elements = document.querySelectorAll(".myClass");
µÇ¼ºó¸´ÖÆ
ʾÀý£º
<p id="myP">This is a paragraph.</p> <p class="myClass">This is another paragraph.</p>
µÇ¼ºó¸´ÖÆ
// »ñÈ¡¾ßÓÐ id Ϊ "myP" µÄÔªËØ const pElement = document.getElementById("myP"); // »ñÈ¡ËùÓоßÓÐÀàÃû "myClass" µÄÔªËØ const elements = document.getElementsByClassName("myClass"); // »ñÈ¡µÚÒ»¸ö¾ßÓÐÀàÃû "myClass" µÄÔªËØ const firstElement = document.querySelector(".myClass");
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇjsÔõô»ñÈ¡ÔªËصÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡