我正在写一个Greasemonkey脚本,它应该做一件简单的事情:如果<h2>
元素(页面上总是只有一个)和第一次出现<h3>
之间有某个字符串元素(可以是其中几个或根本没有),然后......(我已经完成了这部分)。
我很感激有条件的帮助。
答案 0 :(得分:2)
var masterString = document.body.innerHTML;
var start = masterString.indexOf('<h2>');
var end = masterString.indexOf('<h3>'); // Will find the position of first occurance of h3 - if any
if (end <0)
// there is no h3
else {
var searchMe = masterString.substr(start,end); // now this is the portion of your HTML body that you want to look for a string match
var numberOfOccurances = searchMe.match(/yourString/g);
}
答案 1 :(得分:2)
现在我恰巧熟悉Mikhail正在研究的代码。
基本结构是
<div>
<div>
<h2>Something</h2>
<td>We want to search for the string here</td>
<td>We want to search for the string here</td>
</div>
<div>
<h3>Something else</h3>
<td>May contain the same string, but we are only interested if it contains in previous div .</td>
<td>May contain the same string, but we are only interested if it contains in previous div .</td>
</div>
</div>
字符串不是h2的子元素,所以我认为getElementsByTagName不起作用。不幸的是,实际上有数百个具有相同类ID的div层。在这种特殊情况下,标题是代码中唯一的唯一细节。所以在我看来,最好的方法是首先找到h2,转到它的父级并将文本存储为字符串。然后在文本中搜索字符串。这样的东西......
<script>
var searcharea = jQuery('h2').parent('div').text();
var searchstring = "superstring";
if( searcharea.indexOf( searchstring ) != -1 )
alert("exchange alert to your own things");
</script>
至于h3,它可能存在也可能不存在,但由于它不是兄弟,它并不重要。 :)谢谢大家抽出时间回答我们的问题。
答案 2 :(得分:0)
您是否尝试过getElementsByTagName
?
答案 3 :(得分:0)
//get all the H2 elements
var h2 = document.getElementsByTagName("h2");
//Just in case there are more than one...
for(var i = 0; i < h2.length; i++){
//check for the certain string
if(h2[i].textContent == "SOME TEXT"){
//get the first h3 element and do something...
var h3 = document.getElementsBtTagName("h3")[0]; //first occurrence of H3
//DO SOMETHING
}
https://developer.mozilla.org/en-US/docs/DOM/Node.textContent
https://developer.mozilla.org/en-US/docs/DOM/element.getElementsByTagName