简体   繁体   中英

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.

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"]');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM