Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

jquery - Find parent element of string in Javascript

I'm attempting to find a specific string in a document which potentially can have the text split by other tags (i.e. "< p > This is an < span > example < /span > < /p >"), where I would want to find the string "This is an example" in a much larger document and return the first parent element in belongs to (in this case, a < p > tag)

I wrote some code to find a string's index in an arbitrary web document...in such a way that it hopefully accommodates the string being split. It returns the index where the string starts. I'm wondering how to either do this more efficiently OR if this is a decent way, I'm wondering how, given the index of a string in a $("body").html() string, how to retrieve the parent element containing that index.

EDIT: Perhaps this was unclear. I am looking for the parent of a string in a document, and I cannot make any assumptions about where the string may be or what tag its parent may be. So, I call $("body").html() and attempt to find the index of the substring in the html "string". Probably certainly inefficient, I'm really desperate for help.
function get_string_parent(str) { 
    var p = null;
    var split = str.split(' ');
    var body_html = $("body").html();
    var lower_ind = 0;
    var upper_ind = split.length;
    var STOPPING_LENGTH = 3; //give up after not finding string of length 3... 
    var ind = -1;
    do {  //shrink string until a snippet is found
        ind = body_html.indexOf(split.slice(lower_ind, upper_ind).join(' '));
        upper_ind--;
    }
    while (ind < 0 && upper_ind > STOPPING_LENGTH);
    console.log("FOUND AT INDEX: ", ind);
    //console.log("String around index: ", body_html.slice(ind - 10, ind + 10));
    //I"M UNSURE OF, GIVEN A VALID "IND", how to get the parent element at that index

    return p;

Thanks for your time, I'm not familiar with webdev and I'm almost certainly in over my head.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This will get you started. You can use :contains() selector for finding string in html.

function getStringParent(str) { 
  return $("p:contains('"+ str +"')");
}
var parent = getStringParent('This is an  example');
console.log('found ' + parent.length + ' items' + '
');
console.log(parent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> This is an <span> example </span> </p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...