user1410081
user1410081

Reputation:

JavaScript get all class names text using Android webview

I'm trying to get the text from a class by doing this:

 myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            myWebView.setWebViewClient(null);
            myWebView.loadUrl("javascript:window." +
                    "HTMLOUT.processHTML('<div>'+document.getElementsByClassName('text Phil-1-3')[1].innerHTML+'</div>');");
        }
    });
    myWebView.loadUrl("https://www.biblegateway.com/passage/?search=Philippians+1%3A3&version=ESVUK");

However it only gets the first element. I think because of

[0].innerHTML

?

I want to get all class name's text but I don't have an idea how to do that. Any ideas? I would gladly appreciate your help. Thanks!

Upvotes: 0

Views: 793

Answers (1)

Mikhail Naganov
Mikhail Naganov

Reputation: 6871

Exactly -- you are getting what you are asking for :)

getElementsByClassName returns an 'array-like object', and you can use Array.reduce function in order to iterate over its elements and concatenate their innerHTMLs:

Array.prototype.reduce.call(
    document.getElementsByClassName('...'),
    function(a, b) { return a + '<div>' + b + '</div>' },
    '');

Applying to your example:

myWebView.loadUrl("javascript:window." + 
    "HTMLOUT.processHTML(" + 
    "  Array.prototype.reduce.call(" +
    "    document.getElementsByClassName('text Phil-1-3'), " +
    "    function(a, b) { return a + '<div>' + b + '</div>' }, " +      
    "    '')" + 
    ");");

Upvotes: 1

Related Questions