Search code examples
javascriptandroidhtmlwebviewhref

How to get an HTML element by his href using javascript?


I'm building an webview application which has unwanted html sections/blocks/buttons for my android app.

I want to remove them by overriding onPageFinished(). I've succeeded doing it for some elements.

On the webpage i have this element:

<footer>
    ...
    <a href="http://www.randomlink.com" style=""></a>
    ...
  </footer>

My java code:

public void onPageFinished(WebView view, String url) {        
        view.loadUrl("javascript:document.getElementsByTagName('a')[98].style.display=\"none\";");
   }

It does work with 98... but I don't want magic numbers, i want to be able to catch it by his href so it works in any page.

[edit] Forgot to say that I'm working with a 3rd party webpage - leaving me no choice but to block unwanted implementations on my webview application.

Any help is appreciated. Cheers.


Solution

  • You can get it by it's attribute.

    var aTags = document.getElementsByTagName("a");
    var wantedElement = null;
    
    for(var i = 0; i < aTags.length; i++)
    {
        if(aTags[i].getAttribute("href") == "www.example.com")
        {
            wantedElement = aTags[i];
            //break out of loop
        };
    }
    

    With jQuery:

    var element = $('a[href$="Your href"]');