简体   繁体   中英

Clicking a HREF using javascript

I'm in a situation where I can't use jquery to select an element inside the DOM and trying to figure out how to use Javascript to do it.

The jquery path is $('.link-linkedin a').attr('href');

I'm trying to get to the href and open it in a new tab.

I found this - http://javascript.info/tutorial/searching-elements-dom and tried doing

var elem = document.getElementsByClassName('link-linkedin')
var list = elem.getElementsByTagName('a')

But I'm getting the error:

Uncaught TypeError: elem.getElementsByTagName is not a function(…)

Is there a better way to do this?

// where `linkIndex` , `aIndex` are index of each respective element
// to be selected from collections returned by `.getElementsByClassName` ,
// `.getElementsByTagName`
var linkIndex = 0, aIndex = 1;
var elem = document.getElementsByClassName('link-linkedin')[linkIndex];
var list = elem.getElementsByTagName('a')[aIndex];
var href = list.href;

You don't need javascript for that. Just add target="_blank" to your anchor element.

Something like this:

<a href="whatever" target="_blank">whatever</a>

This will open the link on a new tab when you click it.

I am going to go ahead and put this as an answer. First, it is unclear what you are trying to do, but some things will help your code.

Put semi-colons at the end of each instruction.

Do not call a variable "list" - list of what - use better naming, and avoid words that could be used as a reserved word.

If you are trying to reference an element in the DOM, give it an ID, and then use document.getElementById to get at it.

<a href="~/Customers.html" id="LinkToCustomers" target="_blank">Customers</a>

And to reference it in your javascript:

var ListOfCustomers = document.getElementById("LinkToCustomers");
window.open(ListOfCustomers.getAttribute("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