[英]Find <a> tags using jquery with no span of particular text in it
[英]Finding text within a span that contains tags and white spacing using jquery
我有以下跨度,其中包含標簽內的空格和文本 - 在這種情況下是 sup 標簽和 ap 標簽:
<span class="teamName">
Dr.<sup>J</sup>
W
Smith
<br>
<p class="department">Throat specialist</p>
</span>
我正在嘗試提取“博士”。 JW Smith' 從元素,但無法弄清楚如何做到這一點。 到目前為止,我有這個:
jQuery('span[class="teamName"]').text()
,它給了我以下輸出:
"
Dr.J
W
Smith
Throat specialist
"
就我所知,我正在考慮剝離白色間距並將每個單詞放在一個數組中,然后刪除最后一個條目,有人對如何解決這個問題有任何想法嗎?
最簡單的方法可能是克隆元素,從中刪除br
和p
,然后獲取它的文本,用一個空格替換任何空格,然后修剪它:
// Here I'm assuming you have more than one // of these, so this produces an array var names = jQuery("span.teamName") .clone() .find("br, p").remove().end() .map(function() { return $(this).text().replace(/\\s+/g, " ").trim(); }).get(); console.log(names);
<span class="teamName"> Dr.<sup>J</sup> W Smith <br> <p class="department">Throat specialist</p> </span> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
如果你只有一個,我們可以避開map
:
// Here I'm assuming you have more than one // of these, so this produces an array var name = jQuery("span.teamName") .clone() .find("br, p").remove().end() .text() .replace(/\\s+/g, " ") .trim(); console.log(name);
<span class="teamName"> Dr.<sup>J</sup> W Smith <br> <p class="department">Throat specialist</p> </span> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
您可以使用clone()
函數
var cloned = $('.teamName').clone(); cloned.find('p').remove(); console.log(cloned.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="teamName"> Dr.<sup>J</sup> W Smith <br> <p class="department">Throat specialist</p> </span>
這可能對你有用。
var $span = $('.teamName').clone(); $span.find('p').remove(); alert($span.text().replace(/[ \\n]+/g, ' '));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.