在Javascript中查找字符串的父元素 [英] Find parent element of string in Javascript

查看:17
本文介绍了在Javascript中查找字符串的父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在文档中查找特定字符串,该字符串可能会使文本被其他标签分割(即< p > 这是一个 < span > 示例 </span > <;/p >"),我想在其中找到字符串This is an example"在一个更大的文档中并返回属于的第一个父元素(在这种情况下,一个 < p > 标签)

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)

我编写了一些代码来在任意 Web 文档中查找字符串的索引...以这样一种方式,它有望容纳被拆分的字符串.它返回字符串开始的索引.我想知道如何更有效地做到这一点,或者如果这是一种体面的方式,我想知道如何,给定 $(body").html() 字符串中字符串的索引,如何检索包含该索引的父元素.

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.

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;

感谢您抽出宝贵时间,我对 webdev 并不熟悉,而且我几乎可以肯定.

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

推荐答案

这会让你开始.您可以使用 :contains() 选择器在html.

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' + '\n');
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>

这篇关于在Javascript中查找字符串的父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆