Find parent element of string in Javascript

后端 未结 3 1789
醉话见心
醉话见心 2021-01-28 17:05

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 < /s

相关标签:
3条回答
  • 2021-01-28 18:04

    Use padolsey's findAndReplaceDOMText tool and pass it the replace option so that it returns the node you're looking for.

    0 讨论(0)
  • 2021-01-28 18:10

    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>

    0 讨论(0)
  • 2021-01-28 18:12

    You need recursion for this:

    function recursivelySearchString(str,from){
        if(from.textContent.indexOf(str)==-1)
            return null // doesn't contain the string, stop
    
        var children = Array.from(from.children)
        if(children.length>0){
            // current element has children, look deeper
            for(var i=0;i<children.length;i++){
                var found = recursivelySearchString(str, children[i])
                if(found)
                    return found
            }
        }
    
        // none of the children matched, return the parent
        return from
    }
    

    Calling recursivelySearchString('foobar',document.body) will return the closest element containing the phrase. Note it will return the element wrapped in a jQuery selector. If nothing is found it returns null.

    Example:

    function recursivelySearchString(str,from){
        if(from.textContent.indexOf(str)==-1)
            return null // doesn't contain the string, stop
    
        var children = Array.from(from.children)
        if(children.length>0){
            // current element has children, look deeper
            for(var i=0;i<children.length;i++){
                var found = recursivelySearchString(str, children[i])
                if(found)
                    return found
            }
        }
    
        // none of the children matched, return the parent
        return from
    }
    
    var found = recursivelySearchString('dolores',document.body)
    found.style.backgroundColor = 'yellow'
    <div>
      <p>
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      </p>
      <p>
        At vero eos et accusam et <span>justo duo dolores et ea rebum.</span>
        Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
      </p>
    </div>

    0 讨论(0)
提交回复
热议问题