상세 컨텐츠

본문 제목

[모각코] [JavaScript] 웹브라우저 JavaScript(2)

JavaScripts

by <감귤> 2021. 8. 2. 10:54

본문

※ 본 블로그는 인프런 웹브라우저 JavaScript(자바스크립트) 수업을 듣고 정리한 내용입니다.

jQuery Object란?

jQuery 함수의 return 값으로 jQuery함수를 이용해서 선택한 element들에 대해서 처리할 작업을 property로 가지고 있는 객체다.

<html>
  <body>
    <ul>
      <li>html</li>
      <li>css</li>
      <li>javascript</li>
    </ul>
  </body>
</html>

F12(개발자 도구)를 열고

let li = $('li')
li
-> [<li>html</li>, <li>css</li>, <li>javascript</li>]

여기서 $()는 jQuery함수이고, 변수 li는 jQuery 객체가 되는 것이다.

li.css('text-decoration', 'underline');

명령어를 사용하면 위에 li태그들에 해당하는 html, css, JavaScript에 style="text-decoration: underline" 이 적용되어서 밑줄이 그어진다. 이때 우리눈에는 보이지 않는 암시적 반복이 적용되어 한줄의 명령어로 효율적으로 다수의 태그에 영향을 줄 수 있는것이다.

암시적 반복이란?

jQuery 객체의 가장 중요한 특성은 암시적인 반복을 수행한다는 것이다. DOM과 다르게 jQuery 객체의 메소드를 실행하면 선택된 엘리먼트 전체에 대해서 동시에 작업이 처리된다.

암시적 반복은 값을 설정할 때만 동작한다. 값을 가져올 때는 선택된 엘리먼트 중 첫번째에 대한 값만을 반환한다.

//첫번째, 두번째 인자 값 있음
ls.css('text-decoration', underline); //text-decoration이라는 효과는 underline이라는 값을 갖는다(설정)
-> [<li>html</li>, <li>css</li>, <li>JavaScrpit</li>]

//첫번째 인자만 값 있음
ls.css('text-decoration'); //text-decoration이라는 효과의 값을 가져오기
->"underline"

체이닝(Chaining)이란?

chainig이란 선택된 엘리먼트에 대해서 연속적으로 작업을 처리할 수 있는 방법이다.

<ul>
    <li>html</li>
    <li>css</li>
    <li>JavaScript</li>
</ul>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
    console.log($('li').length); // 3
    console.log($('li')[0]);     // <li>html</li>
    let li = $('li');
    for(let i=0; i<li.length; i++){
        console.log(li[i]);     // <li>html</li> <li>css</li> <li>JavaScript</li>
    }
</script>

위 코드에서 볼 수 있듯이 jQuery객체는 조회된 element가 담겨있고, jQuery객체는 일종의 유사배열의 형태로 조회된 element를 가지고 있기 때문에 배열처럼 사용해서 element를 가져올 수 있다.

<ul>
    <li>html</li>
    <li>css</li>
    <li>JavaScript</li>
</ul>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
    console.log($('li').length); // 3
    console.log($('li')[0]);     // <li>html</li>
    let li = $('li');
   for(let j=0; j<li.length; i++){
      console.log(li[j].constructor); // li[i]는 어떤 객체인가?를 알아보기 위함(.constructor)
   }
</script>
// 결과
function HTMLElement() { [native code] }
function HTMLElement() { [native code] }
function HTMLElement() { [native code] }

위 결과를 통해 알 수 있듯이 li[0], li[1], li[2]가 의미하는 객체들은 jQuery객체가 아니라 DOM객체라는 것이다 !!

따라서 지금 상황에서 위 console.log문장을 console.log(li[j].css('color', 'red'));로 바꾸게 되면
TypeError: undefined is not a function에러가 뜬다. 즉, li[j]객체는 DOM객체이기 때문에 내장함수로 css가 존재하지 않는 다는 뜻이다.
console.log($(li[j]).css('color', 'red')) $()라는 jQuery함수를 사용해서 li[j]라는 html element에 해당하는 jQuery객체를 return해주기 때문에 이제는 jQuery 내장함수(ex. css)를 사용할 수 있다.

jQuery객체 API

API(Application Programing Interface)는 객체를 제어할 수 있는 method나 property들의 집합이다.

https://api.jquery.com이 사이트를 참고하면 다양한 jQuery API를 확인할 수 있다.

관련글 더보기