Ao C Ao C - 1 year ago 88
Javascript Question

Go Through innerHTML to Find A Tag with Certain Class

I'm curious as to what the DRYest approach to grabbing an A tag with a certain class is if the A tag is buried within the innerHTML of an element. The innerHTML contains all sorts of divs and other A tags if that's necessary to know. Below is an example of what I'm talking about:

var content = something[0].innerHTML;
// I would want to see whether an A tag with say a certain class "button" exists within "content" then store that A tag in another variable.

Answer Source

Using innerHTML isn’t the best way to do this. Try:

var button = something[0].querySelector('a.button');

button will be null if there’s no match.

See also the docs for querySelector.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download