Javascript 通过内部文本获取所有元素
我遇到了一个问题: 我想在html文档中搜索字符串。到目前为止,我尝试了window.find(..)方法,但是我无法返回找到的元素的节点。例如,我可以突出显示所有匹配的文本。 但是我想把所有的节点放在一个数组中,但是我找不到一个方法,它可以返回我所选文本的节点。 下面的代码只突出显示匹配的文本,我想得到它的(父)节点Javascript 通过内部文本获取所有元素,javascript,Javascript,我遇到了一个问题: 我想在html文档中搜索字符串。到目前为止,我尝试了window.find(..)方法,但是我无法返回找到的元素的节点。例如,我可以突出显示所有匹配的文本。 但是我想把所有的节点放在一个数组中,但是我找不到一个方法,它可以返回我所选文本的节点。 下面的代码只突出显示匹配的文本,我想得到它的(父)节点 function doSearchAdam(text) { if (window.find && window.getSelection) { docum
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);
}
}
}
谢谢大家!
Adam将上述注释中的代码放入代码标记中,以提高可读性
$(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"));
}
将上面注释中的代码放入代码标记中,以提高可读性
$(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"));
}
你会使用jquery吗?那你也可以做类似的事耶,谢谢!非常有用!以下是代码,以防有人对解决方案感到疑惑:'$(document).ready(function(){$(“#findButton”)。单击(function(){myFunction();});函数myFunction(){var matchedPages=new Array();$(“.Page”).filter(函数(){if($(this).text().indexOf($(“#findText”).val()>=0){/$(“#findText”).value()console.log($(this));matchedPages.push($(this));});console.log(matchedPages)(matchedPages)(matchedPages.log)(matchedPages[1].attr(“id”);}您可以使用jquery吗?那你也可以做类似的事耶,谢谢!非常有用!以下是代码,以防有人对解决方案感到疑惑:'$(document).ready(function(){$(“#findButton”)。单击(function(){myFunction();});函数myFunction(){var matchedPages=new Array();$(“.Page”).filter(函数(){if($(this).text().indexOf($(“#findText”).val()>=0{/$(“#findText”).value()console.log($(this));matchedPages.push($(this));});console.log(matchedPages)(matchedPages);console.log(matchedPages[1].attr(“id”);}'