programing

jQuery를 사용하여 텍스트 노드를 선택하려면 어떻게 해야 합니까?

kingscode 2023. 2. 1. 22:06
반응형

jQuery를 사용하여 텍스트 노드를 선택하려면 어떻게 해야 합니까?

요소의 모든 하위 텍스트 노드를 jQuery 컬렉션으로 가져옵니다.그것을 하는 가장 좋은 방법은?

jQuery에는 편리한 기능이 없습니다.결합해야 합니다.contents()자노드만 제공되지만 텍스트노드가 포함되어 있습니다.find()모든 하위 요소를 제공하지만 텍스트 노드는 제공하지 않습니다.제가 생각해낸 것은 다음과 같습니다.

var getTextNodesIn = function(el) {
    return $(el).find(":not(iframe)").addBack().contents().filter(function() {
        return this.nodeType == 3;
    });
};

getTextNodesIn(el);

주의: jQuery 1.7 이전 버전을 사용하는 경우 위의 코드는 작동하지 않습니다.이 문제를 해결하려면 로 대체합니다.andSelf()을 위해 추천되지 않는다.addBack()1.8 이후.

이는 순수한 DOM 메서드에 비해 다소 비효율적이며 jQuery의 함수 오버로드에 대한 추악한 회피책(@rabidsnail에 의한 코멘트)을 포함해야 합니다.따라서 단순한 재귀 함수를 사용하는 비jQuery 솔루션이 여기에 있습니다.includeWhitespaceNodes파라미터는 공백 텍스트 노드를 출력에 포함할지 여부를 제어합니다(jQuery에서는 자동으로 필터링 제외됨).

업데이트: 포함 시 버그 수정Whitespace Nodes는 거짓입니다.

function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [], nonWhitespaceMatcher = /\S/;

    function getTextNodes(node) {
        if (node.nodeType == 3) {
            if (includeWhitespaceNodes || nonWhitespaceMatcher.test(node.nodeValue)) {
                textNodes.push(node);
            }
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
}

getTextNodesIn(el);

Jauco가 좋은 솔루션을 코멘트에 올렸기 때문에, 여기에 카피합니다.

$(elem)
  .contents()
  .filter(function() {
    return this.nodeType === 3; //Node.TEXT_NODE
  });
$('body').find('*').contents().filter(function () { return this.nodeType === 3; });

jQuery.contents() 를 사용하여 모든 하위 텍스트 노드를 찾을 수 있습니다.조금 비틀면 손자손녀 텍스트 노드도 찾을 수 있습니다.재귀 불필요:

$(function() {
  var $textNodes = $("#test, #test *").contents().filter(function() {
    return this.nodeType === Node.TEXT_NODE;
  });
  /*
   * for testing
   */
  $textNodes.each(function() {
    console.log(this);
  });
});
div { margin-left: 1em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="test">
  child text 1<br>
  child text 2
  <div>
    grandchild text 1
    <div>grand-grandchild text 1</div>
    grandchild text 2
  </div>
  child text 3<br>
  child text 4
</div>

jsFiddle

허용된 필터 기능으로 빈 텍스트 노드를 많이 받았습니다.공백이 아닌 텍스트 노드를 선택하는 데만 관심이 있는 경우,nodeValue조건부로filter단순한 기능처럼$.trim(this.nodevalue) !== '':

$('element')
    .contents()
    .filter(function(){
        return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
    });

http://jsfiddle.net/ptp6m97v/

또는 내용이 공백처럼 보이지만 그렇지 않은 이상한 상황을 피하기 위해(소프트 하이픈 등)&shy;문자, 줄 바꿈\n, 탭 등)을 사용하여 정규 표현을 사용해 볼 수 있습니다.예를들면,\S는 공백 이외의 문자와 일치합니다.

$('element')
        .contents()
        .filter(function(){
            return this.nodeType === 3 && /\S/.test(this.nodeValue);
        });

모든 자녀가 요소 노드 또는 텍스트 노드 중 하나라고 가정할 수 있는 경우, 이것이 하나의 해결책입니다.

모든 하위 텍스트 노드를 jquery 컬렉션으로 가져오려면:

$('selector').clone().children().remove().end().contents();

텍스트 이외의 자식이 제거된 원본 요소의 복사본을 가져오려면:

$('selector').clone().children().remove().end();

웬일인지 그래.contents()나에게 효과가 없었기 때문에, 만약 그것이 당신에게 효과가 없다면, 여기 제가 만든 해결책이 있습니다.jQuery.fn.descendants를 선택할 수 있습니다.

사용.


텍스트 노드 및 요소 노드를 포함한 모든 하위 노드 가져오기

jQuery('body').descendants('all');

텍스트 노드만 반환하는 모든 하위 노드 가져오기

jQuery('body').descendants(true);

요소 노드만 반환하는 모든 하위 노드 가져오기

jQuery('body').descendants();

커피스크립트 원본:

jQuery.fn.descendants = ( textNodes ) ->

    # if textNodes is 'all' then textNodes and elementNodes are allowed
    # if textNodes if true then only textNodes will be returned
    # if textNodes is not provided as an argument then only element nodes
    # will be returned

    allowedTypes = if textNodes is 'all' then [1,3] else if textNodes then [3] else [1]

    # nodes we find
    nodes = []


    dig = (node) ->

        # loop through children
        for child in node.childNodes

            # push child to collection if has allowed type
            nodes.push(child) if child.nodeType in allowedTypes

            # dig through child if has children
            dig child if child.childNodes.length


    # loop and dig through nodes in the current
    # jQuery object
    dig node for node in this


    # wrap with jQuery
    return jQuery(nodes)

Javascript 버전에서의 드롭

var __indexOf=[].indexOf||function(e){for(var t=0,n=this.length;t<n;t++){if(t in this&&this[t]===e)return t}return-1}; /* indexOf polyfill ends here*/ jQuery.fn.descendants=function(e){var t,n,r,i,s,o;t=e==="all"?[1,3]:e?[3]:[1];i=[];n=function(e){var r,s,o,u,a,f;u=e.childNodes;f=[];for(s=0,o=u.length;s<o;s++){r=u[s];if(a=r.nodeType,__indexOf.call(t,a)>=0){i.push(r)}if(r.childNodes.length){f.push(n(r))}else{f.push(void 0)}}return f};for(s=0,o=this.length;s<o;s++){r=this[s];n(r)}return jQuery(i)}

미확보 Javascript 버전 : http://pastebin.com/cX3jMfuD

은 작은 크로스 입니다.Array.indexOf폴리필

다음과 같이 할 수도 있습니다.

var textContents = $(document.getElementById("ElementId").childNodes).filter(function(){
        return this.nodeType == 3;
});

위의 코드는 특정 요소의 직계 하위 노드에서 textNode를 필터링합니다.

모든 태그를 제거하고 싶다면, 이것을 시도해 보세요.

기능:

String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}

사용방법:

var newText=$('selector').html().stripTags();

옛날이야.contents()텍스트 노드를 반환하기 위해 동작하는 것처럼 보입니다.텍스트 노드가 될 수 있도록 셀렉터를 주의해 주세요.

들어 내을 TD로 .pre태그가 부착되어 문제가 없었습니다.

jQuery("#resultTable td").content().wrap("<pre/>")

같은 문제를 안고, 다음과 같이 해결했습니다.

코드:

$.fn.nextNode = function(){
  var contents = $(this).parent().contents();
  return contents.get(contents.index(this)+1);
}

사용방법:

$('#my_id').nextNode();

★★★와 같다.next()텍스트 노드도 반환합니다.

언급URL : https://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery

반응형