pufAmuf
pufAmuf

Reputation: 7805

Target link by attribute

I'm trying to activate a link via javascript which looks like this:

<a class="second_link nobold" data-type="via_mail" href="http://swap.mtr.com/index.php?id=10&ctid=546432#">Send via mail</a>

I thought about targeting the link via class, but there are numerous links with that class.
How do I activate the link through data-type="via_mail"?

Upvotes: 0

Views: 59

Answers (4)

Ruslan
Ruslan

Reputation: 10145

this javascript should work in every browser:

var anchors = document.getElementsByTagName("a");
for (i=0; i < anchors.length; i++) {
    if (anchors[i].getAttribute("data-type") == "via_mail") {
        // GOTCHA!
    }
}

if you can use jQuery attribute selector:

$('a[data-type="via_mail"]');

Upvotes: 0

ZER0
ZER0

Reputation: 25322

As showed by others, if use / can use jQuery, you can simple have:

var link = $("a[data-type='via_mail']")[0];

However, if the browser you're going to support implements querySelector/querySelectorAll, you can simply have:

var link = document.querySelector("a[data-type='via_mail']");

Without additional library.

Upvotes: 1

marteljn
marteljn

Reputation: 6516

Depending on what browsers you plan on supporting you can do querySelectorAll with most modern browsers:

document.querySelectorAll("a[data-type='via_mail']");

Upvotes: 1

gdoron
gdoron

Reputation: 150253

If you target only modern browser you can use document.querySelector

document.querySelector('a.second_link[data-type="via_mail"]').click();

If you can use jQuery:

$('.second_link[data-type="via_mail"]').click();

If non of the above helps, you need to write some more...

var ele = document.getElementsByTagName('a');
for (var i = 0; i < ele.length; i++)
    if (ele[i].getAttribute('data-type') == 'via_mail')
        ele[i].click(); 

Live DEMO

Upvotes: 1

Related Questions