在类中搜索特定的字符串

时间:2019-06-02 14:10:08

标签: javascript jquery html xpath

我有这段HT​​ML。 <div class="text">helloworld</div>

因此,当在某个类中找到该字符串时,我想在该类的“文本”中搜索该字符串。执行一个函数,但仅当找到字符串时,如果找不到该字符串,则只需打印console.log('not found.')并简单地打印出该字符串即可。

我的代码如下所示。

var timerVar = setInterval (function() {DoMeEverySecond (); }, 2000); // << set to 2 seconds.

function DoMeEverySecond ()
{
var xpathResult = document.evaluate("(//text()[contains(., 'helloworld')]) [1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var node=xpathResult.singleNodeValue;
if (node==null)
console.log('Not found')
else
console.log('found');
}

此代码有效,但是会搜索所有类。我只想搜索“文本”类

1 个答案:

答案 0 :(得分:0)

请检查以下代码,首先,您将找到类包含'text'的所有节点(请参阅this Q&A)。之后,每个节点都包含单词'helloworld'

function getElementsByXPath(xpath, parent)
{
    let results = [];
    let query = document.evaluate(xpath, parent || document,
        null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (let i = 0, length = query.snapshotLength; i < length; ++i) {
        results.push(query.snapshotItem(i));
    }
    return results;
}

function DoMeEverySecond ()
{
	var nodes = getElementsByXPath("//*[contains(@class,'text')]", document);
	for(var i =0; i< nodes.length; i++){
		var xpathResult = document.evaluate("(text()[contains(., 'helloworld')]) [1]", nodes[i], null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		var node=xpathResult.singleNodeValue;
		if (node==null)
			console.log('Not found')
		else
			console.log('found');
	}
	
}

var timerVar = setInterval (function() {DoMeEverySecond (); }, 2000); // << set to 2 seconds.