Web/JavaScript
[Javascript]not연산자를 이용한 querySelectorAll 필터링
금백조
2023. 3. 26. 18:27
반응형
서론
input 태그들을 querySelectorAll로 가져와 value를 초기화해주려고 했는데 radio type이 아닌 input만 가져와서 초기화를 해야했습니다. 이 과정에서 알게된 not 연산자를 이용한 querySelectorAll 필터링 방법에 대해 소개하겠습니다.
본론
AND 조건
해석 : input 태그 중 radio type이 아니고 class가 test가 아닌 input 전부 가져오기
const inputs = document.querySelectorAll("input:not([type='radio']):not([class='test'])")
OR 조건
해석 : input 태그 중 radio type이 아니거나 class가 test가 아닌 input 전부 가져오기
const inputs = document.querySelectorAll("input:not([type='radio']), input:not([class='test'])")
예제
<!DOCTYPE html>
<html>
<body>
<h2>not 연산자를 이용한 querySelectorAll 필터링 예제</h2>
<form>
<section class='person-info'>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname"><br>
<label for="front_lang">FrontEnd Language:</label><br>
<input type="radio" id="html" name="front_lang" value="HTML" checked>
<label for="html">HTML</label>
<input type="radio" id="css" name="front_lang" value="CSS">
<label for="css">CSS</label>
<input type="radio" id="javascript" name="front_lang" value="JavaScript">
<label for="javascript">JavaScript</label><br><br>
</section>
<input type="button" value="초기화" onClick=initMethod()>
</form>
</body>
</html>
<script>
const initMethod = () => {
const section = document.querySelector("section[class='person-info']");
const inputs = section.querySelectorAll("input:not([type='radio'])");//radio type 아닌 input만 가져오기
inputs.forEach(input => {
input.value="";
});
}
</script>
반응형