Backend/JavaScript

JS Eclipse JavaScript 활용 : 요소를 숨기거나 나타내기

쏠솔랄라 2023. 5. 15. 13:41

 

 

문서에서 요소를 가져오는 JS 함수들

 

 

<style type="text/css">
table, th {
border: 1px solid black;
border-collapse: collapse;
}

.hidden {
display: none;
}

</style>
</head>
<body>

<h1>요소를 숨기거나 나타내기</h1>
<hr>

<div id="box">
<label><input type="checkbox" id="boxOdd">홀수</label>
<label><input type="checkbox" id="boxEven">짝수</label>
</div>

<table id="table">
<tr class="t">
<th>1번째 글자</th>
</tr>
<tr>
<th>2번째 글자</th>
</tr>
<tr id="th">
<th>3번째 글자</th>
</tr>
<tr>
<th>4번째 글자</th>
</tr>
<tr>
<th>5번째 글자</th>
</tr>

</table>

<script type="text/javascript">


// 문서에서 요소를 가져오는 함수들
// 1. id를 통해 특정 요소 하나를 가져오는 함수

const table = document.getElementById("table");
console.log(table);

// 2. class나 태그 이름 등으로 여러 요소 중 하나만 가져오기
// 가장 처음 있는 요소만 가져온다

const th = document.querySelector("th");
console.log(th);

// 3. querySelect : css 선택자 태그명 등으로 조건에 맞는 여러 요소를 리스트로 가져올 수 있다
let thList = document.querySelectorAll("th");
console.log(thList);
// querySelector, querySelectAll은 document가 아닌 요소에도 사용이 가능하다

const box = document.getElementById("box");
console.log(box);

const checkList = box.querySelectorAll('input[type=""]'); // 요소들을 숨기는 등 사용하기 위해 요소를 불러오는 함수들
console.log(checkList); // 콘솔창에 표시하는 태그는 요소들이 올바르게 불러왔는지 확인하기 위한 것임

// document.getElementBy
// Name, Tagname, ClassName
const trList = document.getElementsByClassName('t');
console.log(trList);
console.log(trList[0].children[1]);
thList = document.getElementsByTagName("tr");
console.log(thList);

// 동적 추가
const test1 = document.getElementsByTagName("tr"); // 추가 요소 반영
const test2 = document.querySelectorAll("th"); // 추가 요소 미반영

const newTr = document.createElement("tr"); // tr태그를 생성시키겠다
const newTh = document.createElement("th"); // th태그를 생성시키겠다
newTh.innerText = "6번째 추가된 글자";

newTr.appendChild(newTh);
table.appendChild(newTr);

// 요소 생성

console.log(test1);
console.log(test2);


</script>

 

 

출력화면

 

 

이벤트 만들기

 

 

<style type="text/css">
table, th {
border: 1px solid black;
border-collapse: collapse;
}

.hidden {
display: none;
}

</style>
</head>
<body>

<h1>요소를 숨기거나 나타내기</h1>
<hr>

<div id="box">
<label><input type="checkbox" id="boxOdd">홀수</label>
<label><input type="checkbox" id="boxEven">짝수</label>
</div>

<table id="table">
<tr id="tr1">
<th>1번째 글자</th>
</tr>
<tr id="tr2">
<th>2번째 글자</th>
</tr>
<tr id="tr3">
<th>3번째 글자</th>
</tr>
<tr id="tr4">
<th>4번째 글자</th>
</tr>
<tr id="tr5">
<th>5번째 글자</th>
</tr>

</table>

<script type="text/javascript">

// 참조 대상들 불러오기

const boxOdd = document.querySelector('#boxOdd');
// = document.getElementById(boxOdd);
const boxEven = document.querySelector('#boxEven');
const tr1 = document.querySelector('#tr1');
const tr2 = document.querySelector('#tr2');
const tr3 = document.querySelector('#tr3');
const tr4 = document.querySelector('#tr4');
const tr5 = document.querySelector('#tr5');


// 이벤트 함수 준비
// 이벤트 : 특정 조건/상황이 되었을 때 자동으로 실행하게 만드는 것

// 함수
// const func1 = function func1(a) {};
// console.log(func1);

// func1과 동일한 함수 = const func1 = function func1(a) {};
// const func2 = (a) => {};
// console.log(func2);

const clickHandler = (event) => {
console.log(event.type); // 어떤 이벤트 타입인가?
console.log(event.button); // 어떤 버튼으로 클릭 되었는가?
console.log(event.target); // 무엇을 클릭했는가?
console.log(event.target.checked); // 대상이 체크되어 있는가?

const sameFlag = boxOdd.checked === boxEven.checked;
console.log(sameFlag);
/*
boxOdd boxEven 출력
false false 둘 다 보여주기
true false 홀수만
false true 짝수만
true true 둘 다 보여주기
*/

if(sameFlag) {
tr1.className = '';
tr2.className = '';
tr3.className = '';
tr4.className = '';
tr5.className = '';
} else if (boxOdd.checked){
tr2.className = 'hidden';
tr4.className = 'hidden';
} else if (boxEven.checked) {
tr1.className = 'hidden';
tr2.className = 'hidden';
tr3.className = 'hidden';
}
};

boxOdd.onclick = clickHandler;
boxEven.onclick = clickHandler;

</script>

 

 

출력화면

 

 

=> 

    <h1>요소를 숨기거나 나타내기</h1>
    <hr>
    <div class="box">
        <label><input type="checkbox" id="boxOdd">홀수</label>
        <label><input type="checkbox" id="boxEven">짝수</label>
    </div>
    <table id="table">
        <tr id="tr1"><th>1번째 글자</th></tr>
        <tr id="tr2"><th>2번째 글자</th></tr>
        <tr id="tr3"><th>3번째 글자</th></tr>
        <tr id="tr4"><th>4번째 글자</th></tr>
        <tr id="tr5"><th>5번째 글자</th></tr>
    </table>

<script type="text/javascript">
//참조 대상들 불러오기
const boxOdd = document.querySelector('#boxOdd');
const boxEven = document.querySelector('#boxEven');

const trList = document.querySelectorAll('#table tr');

const clickHandler = (event) => {
// false false  다보여주기
// true false 홀수만
// false  true 짝수만
// true true 다보여주기

const sameFlag = boxOdd.checked === boxEven.checked;

if(sameFlag){
/*
for (let i=0; i<trList.length; i++) {
trList[i].className = '';
}
*/

// forEach함수
// 함수를 인자로 전달하여 지정된 형식에 따라 콜백을 수행한다
// * 콜백 : 어떤 함수가 불러졌을 때 자동으로 다른 함수를 부른다
trList.forEach((e) => e.className = ''); // trList 안의 e를 자동으로 forEach안에 반복적으로 때려넣음

}else if(boxOdd.checked){
trList.forEach((element, index) => {
if (index%2 !=0) {
element.className = 'hidden';
}
});
}else if(boxEven.checked){
trList.forEach((e,i) => {
if(i%2 == 0) {
e.className = 'hidden';
}
});
}
};

boxOdd.onclick = clickHandler;
boxEven.onclick = clickHandler;

</script>

 

 

input radio

 

 

<div class="filderbox">
<label><input type="radio" name="filter id="age10" />10대</label>
<label><input type="radio" name="filter id="age20" />20대</label>
<label><input type="radio" name="filter id="age30" />30대</label>
<label><input type="radio" name="filter id="age40" />40대</label>
</div>

<script type="text/javascript">
const inputList = document.querySelectorAll('input');
/*
console.log(inputList.pop());
NodeList는 배열이 아니다
배열처럼 쓰고 싶다면 배열로 변환해야 한다.
*/

// 배열 변환
inputArr = Array.from(inputList);
inputArr1 = Array.from(inputList);

console.log(inputArr);

//배열에서 쓰이는 함수
console.log(inputArr.slice(0,3)); //배열 자르기
console.log(inputArr.concat(inputArr1)); //배열 더하기
console.log(inputArr);
console.log(inputArr.pop()); //마지막 요소 삭제 후 반환
console.log(inputArr);
console.log(inputArr.shift()); //제일 처음 요소 삭제 후 반환
console.log(inputArr);
console.log(inputArr.push(inputArr1[3])); //마지막 요소에 데이터 추가
console.log(inputArr);
console.log(inputArr.unshift(inputArr1[0])); //제일 처음 요소에 데이터 추가
console.log(inputArr);
 
 inputHandler = (event) => {
 // filter() : 전체 목록 중에 내가 원하는 조건에 맞는 요소만 별도로 묶어서 반환하는 메소드
 // 반드시 true or false값을 반환해야 한다
 console.log(event.target.id);
 
 // checkArr = inputArr.filter(input => { return !input.checked }); // 배열만 가능
 // console.log(checkArr);
 
let checkArr = [];
for(let i = 0; i <inputArr.length; i++){
if(!inputArr[i].checked){
checkArr.push(inputArr[i]);
}
}

console.log(checkArr);
 }
 
//  inputArr.forEach(element => {element.onclick = inputHandler; }); 
inputList.forEach(element => { element.onclick = inputHandler; }); //NodeList와 배열 모두 사용가능
 
 // for (let i=0; i<inputArr.letngth; i++){
 //  inputArr[i].onclick = nputHandler;
 // } // 상위 메서드의 하위 

</script>

 

 

출력화면