Find parent element of string in Javascript

后端 未结 3 1862
醉话见心
醉话见心 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: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

    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

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

    At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

提交回复
热议问题