问题
I'm writing a Greasemonkey script, which should do a simple thing: if there's a certain string between the <h2>
element (always only one on the page) and the first occurrence of an <h3>
element (can be several of them or none at all), then ... (I've already done this part).
I'd be grateful for some help with the conditional.
回答1:
now I just happen to be familiar with the codes Mikhail are working on.
The basic structure are
<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>
The string is not a child of h2, so I don't think getElementsByTagName would work. Unfortunately there are literally hundreds of div layer with same class id. In this particular case heading is the only unique details in the code. So in my opinion the best way is to find h2 first, go to its parent and store text as string. Then search for the string in the text. Soemthing like this...
<script>
var searcharea = jQuery('h2').parent('div').text();
var searchstring = "superstring";
if( searcharea.indexOf( searchstring ) != -1 )
alert("exchange alert to your own things");
</script>
As for h3, it may or may not exist, but since its not a sibling, it doesn't really matter. :) Thank you all for taking your time to answer our question.
回答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);
}
回答3:
Have you tried getElementsByTagName
?
回答4:
//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
来源:https://stackoverflow.com/questions/12785185/greasemonkey-look-for-a-string-between-two-elements