티스토리 뷰

반응형

 

이 글은 아래 사이트를 토대로 작성되었습니다.

 

jQuery Best Practices

jQuery Best Practices Greg Franko About the Speaker JavaScript Engineer at AddThis (We are hiring) Open Source Enthusiast Soon-to-be Author Hates the word HTML5 Contact Details Github: https://github.com/gfranko Twitter: https://twitter.com/GregFranko Link

gregfranko.com

DOM 조작하기

i). 일반적인 경우

// elem 요소의 title 속성을 해당 요소의 text를 통해 변경
$(".container input#elem").attr("title", $(".container input#elem").text());

// elem 요소의 색상을 변경
$(".container input#elem").css("color", "red");

// elem 요소를 fadeOut 처리
$(".container input#elem").fadeOut();
  • 선택자가 길어진다.
  • 필요시마다 .container와 같은 class 선택자를 사용하므로 호출시마다 DOM을 탐색한다.

 

ii). better practice

// elem 요소의 title 속성을 해당 요소의 text를 통해 변경
$("#elem").attr("title", $("#elem").text());

// elem 요소의 색상을 변경
$("#elem").css("color", "red");

// elem 요소를 fadeOut 처리
$("#elem").fadeOut();
  • 불필요한 선택자를 줄인다.
  • id 선택자의 특징을 이용하여 DOM 탐색 효율을 높인다.

 

iii). best practice

// DOM 요소를 변수 elem에 저장
var elem = $("#elem");

// elem 요소의 title 속성을 해당 요소의 text를 통해 변경
elem.attr("title", elem.text());

// elem 요소의 색상을 변경
elem.css("color", "red");

// elem 요소를 fadeOut 처리
elem.fadeOut();

// Chaining을 활용한 경우
// elem.attr("title", elem.text()).css("color", "red").fadeOut();
  • DOM 요소를 변수에 저장하여 캐싱하는 효과를 얻을 수 있다.

'Dev. > javascript' 카테고리의 다른 글

[jQuery] best practice - event handling, ajax  (0) 2021.02.18
[JS] 화살표 함수  (0) 2021.02.17
[jQuery] best practice - jQuery Ready Event  (0) 2021.02.16
[jQuery] substr, substring  (0) 2020.11.19
[JS] 스코프, 클로저, 익명함수  (0) 2020.10.05
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함