[英]Get all elements by inner text
我遇到了一個問題:我想在html文檔中搜索字符串。 到目前為止,我嘗試使用window.find(..)方法,但是無法獲取找到的元素的節點。 例如,我可以突出顯示所有匹配的文本。 但是我想將所有節點都放在一個數組中,而且找不到方法,該方法可以向我返回所選文本的節點。 以下代碼僅突出顯示匹配的文本,我想獲取它的(父)節點。
function doSearchAdam(text) {
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, "yellow");
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, "yellow");
textRange.collapse(false);
}
}
}
多謝你們! 亞當
將上面注釋中的代碼放入代碼標簽中,以提高可讀性。
$(document).ready(function() {
$("#findButton").click(function() {
myFunction();
});
});
function myFunction() {
var matchedPages = new Array();
$(".Page").filter(function() {
if ($(this).text().indexOf($("#findText").val()) >= 0) {
//$("#findText").value() console.log($(this));
matchedPages.push($(this));
}
});
console.log(matchedPages);
console.log(matchedPages[1].attr("id"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.