[英]How do I grab certain text on a page?
這會抓取td標簽等
<script type=”text/javascript”>
var td = document.getElementsByTagName(“td”);
for (var i = 0; i < td.length; i++) {
document.write(‘td #’ + i + ‘<br />’);
}
</script>
我如何等效於獲取某些文本
例如,如果我有
hello world
by world
hello goodbye
yellow submarine
yo hello
我該如何抓住所有文字中的“ hello”
使用jQuery的contains選擇器應該可以幫助您。
JS
$('body').find('*:contains("hello")').each(function(){
var h = $(this).html();
//alert(h);
h = h.replace('hello', '<span class="highlight">hello</span>');
$(this).html(h);
});
HTML
<table>
<tr>
<td>hello some more text</td><td>test</td>
</tr>
</table>
<div>hello testing<div>More data</div></div>
<span>hello</span>
CSS
.highlight{
background-color:yellow;
}
將span標記中的所有“ hello”包裝起來,並給它一個類“ hello”
<span class="hello">hello</span> world
by world
<span class="hello">hello</span> goodbye
yellow submarine
yo hello
使用jQuery
var allHello = $('.hello').text();
您可以做的另一種方法是使用正則表達式,但是如果您知道自己的內容,則不需要它。
屏幕抓取的常用方法是將需要捕獲或搜索的文本放入帶有ID的DIV標簽中。 完成此操作后,您將可以使用DIV標簽ID的getElementsByTagName來獲取整個文本。
希望這很清楚。 如果這不是您想要的,我建議您附加更具體的問題。
我該如何抓住所有文字中的“ hello”
我不確定是否收到問題,但是要抓住“ hello”,您可以執行以下操作:
var td = document.getElementsByTagName('td')[0],
td = (td.textContent || td.innerText || ""),
hello = td.match(/hello/gi);
這將返回帶有所有“ hello”的常規javascript數組?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.