jQuery가있는 요소에서 텍스트를 추출하십시오
-
06-07-2019 - |
문제
jQuery가있는 요소 내부의 텍스트를 추출하고 싶습니다.
<div id="bla">
<span><strong>bla bla bla</strong>I want this text</span>
</div>
나는 강한 태그없이 "이 텍스트를 원한다"텍스트 만 원합니다. 어떻게 할 수 있습니까?
해결책
이 시도...
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
$("#bla span").contents().each(function(i) {
if(this.nodeName == "#text") alert(this.textContent);
});
});
//]]>
</script>
이것은 컨텍스트에서 다른 노드를 제거 할 필요가 없으며 각 반복에 텍스트 노드를 제공합니다.
다른 팁
이것은 (테스트)를합니다 :
var clone = $("#bla > span").clone();
clone.find('strong').remove();
alert(clone.text());
Karim79의 방법에 대한 변형 :
$("span").clone().find("strong").remove().end().text();
또는 다른 태그가 무엇인지 모르고 루트 텍스트를 원한다면 다음과 같습니다.
$("span").clone().children().remove().end().text();
여전히 조금 길지만, 나는 당신이 기대할 수있는만큼 짧다고 생각합니다.
var textFromSpanWithoutStrongTag = $('div#bla > span').text();
업데이트 :
var textFromSpanWithoutTextFromStrongTag =
$('div#bla > span').text().replace($('div#bla > span > strong').text(), '');
업데이트 :
var text = '';
$("div#bla > span").contents().each(function () {
if(this.nodeType == 3) text = text + this.nodeValue; });
FF3, IE8, O10B에서 테스트 : :
<div id="bla">
<span>
<strong>bla bla bla</strong>
I want this
<strong>bla bla</strong>
text
<span>bla bla bla</span>
</span>
</div>
제휴하지 않습니다 StackOverflow