2

For a Google Chrome plugin, I am trying to scroll to a DOM element containing a given string. However, after filtering a selector, I am a little bit lost in the DOM.

$('*', 'body')
    .andSelf()
    .contents()
    .filter(function(){                     
        return this.nodeType === 3;
    })
    .filter(function(){
        // Only match when contains given string anywhere in the text       

        if(this.nodeValue.indexOf(givenString != -1){
            //idArr.push(this.offsetLeft);

            var ele = $(this);
                       $('html, body').animate({
                    scrollTop: ele.offset().top
                     }, 2000);                              
                return true;
            }

            return false;

    });

Whenever I try to get the top offset of ele, I get the top offset of the scrollbar in relation to the document instead. Any ideas? I thought it might be a scoping issues with my use of $this inside the filter, but this inside a filter should refer to the current DOM element.

EDIT:

by calling

var ele=$(this.parentNode);

I was able to get the element that contained the text node

anguyen
  • 467
  • 4
  • 17
  • Maybee this help for you https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView – zloctb Jul 02 '13 at 05:47

2 Answers2

2

Try this:

var matches = $('body, body *').
        addBack().
        contents().
        filter(function(){                     
            return this.nodeType === 3;
        }).
        filter(function(){
        // Only match when contains given string anywhere in the text               
             if(this.nodeValue.indexOf(givenString) != -1)
               return true;
        }).first();

Basically the same filtering you had (I just added a missing parenthesis). This will give you the first (if any) textnode that matches your string. But since you can't get a textnodes position in the DOM directly (refer to this question) you may want to try a simple trick, wrapping it inside a span element and then retrieving the offset to scroll the page:

if(matches.length > 0){
    var offset = $(matches).wrap('<span>').parent().offset().top;
    $('html, body').animate({scrollTop: offset}, 'slow');
}

Fiddle example here

Community
  • 1
  • 1
omma2289
  • 54,161
  • 8
  • 64
  • 68
0
el = $(":not(html, body, div, table, tbody, tr):contains('" + givenString + "')")

This will return the matched elements. Then you can scroll to the element

Bharath
  • 797
  • 6
  • 14