Javascript & JQuery & CSS > Javascript - ¹®¼°´Ã¼ °¡Á®¿À±â - getElementById() , getElementsByName() , getElementsByTagName() , getElemen
µî·ÏÀÏ : 2017-09-08 12:37
Á¶È¸¼ö : 53,815
1. getElementById()
¹®¼°´Ã¼ Áß ID °ªÀ» °¡Á®¿À´Âµ¥ »ç¿ëµÇ´Â ÇÔ¼ö ÀÔ´Ï´Ù.
// ¹®¼ °´Ã¼¸¦ °¡Á®¿É´Ï´Ù.
var header1 = document.getElementById('header_1');
var header2 = document.getElementById('header_2');
// ¹®¼ °´Ã¼ÀÇ ¼Ó¼ºÀ» º¯°æÇÕ´Ï´Ù.
header1.innerHTML = 'with getElementById()';
header2.innerHTML = 'with getElementById()';
<div id="header_1"> Header </div>
<div id="header_2"> Header </div>
ÇÔ¼ö¸¦ ÀÌ¿ëÇØ ³Ñ¾î¿Â º¯¼ö¸¦ °´Ã¼·Î º¯°æÇÏ°í ½ÍÀ» °æ¿ì´Â ¾Æ·¡Ã³·³ ó¸® ÇÏ¸é µË´Ï´Ù.
function test(form_name)
{
var OBJ = eval("document.getElementById('"+ form_name + "')");
}
2. getElementsByName()
¹®¼°´Ã¼ Áß NAME °ªÀ» °¡Á®¿À´Âµ¥ »ç¿ëµÇ´Â ÇÔ¼ö ÀÔ´Ï´Ù.
Àоîµå¸° °´Ã¼´Â ¹è¿·Î ÀúÀåÀÌ µË´Ï´Ù.
window.onload = function () {
alert(document.getElementsByName("point").length);
var OBJ_Point = document.getElementsByName("point");
//º¯¼ö OBJ_Point ´Â ¹®¼ °´Ã¼¸¦ °¡Áö´Â ¹è¿·Î µé¾î°ª´Ï´Ù. ¾Æ·¡Ã³·³ 󸮵˴ϴÙ.
for (var i = 0; i < OBJ_Point.length; i++) {
alert(OBJ_Point[i].value);
}
}
<body>
<input type="text" name="point" value="11" size='10'>
<input type="text" name="point" value="22" size='10'>
<input type="text" name="point" value="33" size='10'>
<input type="text" name="point" value="44" size='10'>
<input type="text" name="point" value="55" size='10'>
</body>
3. getElementsByTagName()
¹®¼¿¡ ÁöÁ¤µÈ ÅÂ±× °´Ã¼¸¦ ³ªÅ¸³À´Ï´Ù. °á°ú´Â ¹è¿ Çü½ÄÀ̵DZ⠶§¹®¿¡ length¿¡¼ »ç¿ëµÇ´Â ű×ÀÇ ¼ö¸¦ °¡Á® ¿À°Å³ª
ű׷Πǥ½ÃµÇ´Â ³»¿ëÀ» º¯°æÇÒ ¼öÀÖ½À´Ï´Ù.
window.onload = function () {
alert(document.getElementsByTagName("input").length);
var OBJ_Point = document.getElementsByTagName("input");
for (var i = 0; i < OBJ_Point.length; i++) {
alert(OBJ_Point[i].type);
}
}
<body>
<input type="text" name="point" value="11" size='10'>
<input type="text" name="point" value="22" size='10'>
<input type="text" name="point" value="33" size='10'>
<input type="text" name="point" value="44" size='10'>
<input type="text" name="point" value="55" size='10'>
</body>
4. getElementsByClassName()
ÁÖ¾îÁø Ŭ·¡½º À̸§ÀÌ ÁÖ¾îÁø ¿ä¼ÒÀÇ ÁýÇÕÀ» ¹ÝȯÇÕ´Ï´Ù.
document °³Ã¼¸¦ È£ÃâÇÏ¸é ·çÆ® ³ëµå¸¦ Æ÷ÇÔÇÏ¿© Àüü ¹®¼¸¦ °Ë»öÇÕ´Ï´Ù. ÀÓÀÇÀÇ ¿ä¼Ò·Î getElementsByClassName¸¦ È£ÃâÇÒ ¼öÀÖ½À´Ï´Ù.
ÀÌ °æ¿ì¿¡´Â ÁÖ¾îÁø Ŭ·¡½º À̸§À» »ç¿ëÇÏ¿© ÁöÁ¤µÈ ·çÆ® ¿ä¼Ò ¾Æ·¡ÀÇ ¿ä¼Ò¸¸ ¹ÝȯÇÕ´Ï´Ù.