본문 바로가기

WebDev

jQuery direct text

jQuery direct text

jQuery.text()명령은 해당 노드의 텍스트 컨텐츠를 가져온다. 상당히 편리하다.
하지만 문제는, 만약 노드가 자식을 가진 경우 자식의 텍스트까지 긁어와버린다는 것이다.
이 문제를 해결한 snippet을 적어둔다. 이 코드는

  1. 자식의 text를 가져오지 않는다. 자신의 text만 추출한다.
  2. null-safe하다. 만약 노드가 text를 가지고 있지 않으면 ''을 반환한다.

snippet

var directText = function (jq) {
    var textNode = jq.contents().filter(function () {
        return this.nodeType == 3;
    })[0];
    return textNode ? textNode.nodeValue : '';
};
// var nickname = directText($('#nickname'));


'WebDev' 카테고리의 다른 글

Elasticbeanstalk docker Using Images From a Private Repository (new)  (0) 2016.06.04
AWS 인증서 업로드  (0) 2016.03.25
AngularJS  (0) 2016.03.11
css same width, height  (0) 2016.03.10
javascript object copy  (0) 2016.03.08