当前位置: 动力学知识库 > 问答 > 编程问答 >

Javascript: Finding a certain Element and ripping off parts of the link

问题描述:

I am totally new to JavaScript coding, and I hope you can help me.

In my source code there is a link with the content shortlink in its attribute.

<link rel='shortlink' href='http://example.com/?p=14286' />

From this element I want to read out the href link, and rip off everything before the ?p=14286 query.

How is this possible? Using document.getElementsByAttribute I failed..

网友答案:

You could just split the URL.

var link = document.querySelector("link"); //use All for a list
var link = link.href.split("?");
var url = link[0];
var params = link[1];
网友答案:

You can select any elment by its attributes using the css attribute selector [attribute=value].

So you can get the href URL with this statement:

document.querySelector("link[rel=shortlink]").href
网友答案:

You can use document.querySelectorAll() to find all elements matching a CSS selector, and use a CSS3 attribute selector to find all elements with the specified string in their rel attribute.

As for getting the part of the link you want, it's basic string manipulation which has many answers and resources on this site and elsewhere.

网友答案:

If you can change the HTML then add an id to the link and use document.getElementById. If you can't then get all links with document.getElementsByTagName and search for rel='shortlink'.

// Get all link tags
var links = document.getElementsByTagName('link');

// Search link tags for rel='shortlink'
for (var i = 0; i < links.length; i++) {
  var link = links[i];
  if (link.getAttribute('rel') == 'shortlink') {
    var href = link.getAttribute('href');
    var query_start = href.indexOf('?');
    var query = href.substring(query_start);
    alert(query);
    break;
  }
}

// Alternatively we can use an id
var myLink = document.getElementById('myLink');
var href = myLink.getAttribute('href');
href = href.substr(href.indexOf('?'));
alert(href);
<link rel='shortlink' href='http://example.com/?p=14286' />
<link rel='otherlink' href='http://example.com/?p=12345' />
<link rel='otherlink' href='http://example.com/?p=12345' id="myLink"/>
分享给朋友:
您可能感兴趣的文章:
随机阅读: