Get the value of the href attribute of the <a> tag without jQuery

Is there any way how to get the href attribute in the tag β€œa” from the string value without jQuery? I have a line with (for example) this content - <a href="www.something"> .

How can I get the value of the href attribute for a variable?

+4
source share
3 answers

I have a line with (for example) this content - <a href="www.something">

If this is really a string:

 var s = '<a href="www.something">'; 

Then you can use the regex with the .match() method :

 var href = s.match(/href="([^"]*)/)[1]; // href is now www.something 

If this is an element on your page, check out TJ Crowder's answer (I don't need to duplicate this information here).

+4
source

If you really have it as a string, then it refers to nnnnnn's answer .

Or alternately if you are in a browser environment:

 var str = '<a href="www.something">'; var div = document.createElement('div'); div.innerHTML = str + "</a>"; // Make it a complete tag var link = div.firstChild.getAttribute("href"); 

If you have an actual element on a page created using this markup, then:

If you have a link to an element, you can get href from it as follows:

 var link = theElement.href; // or var link = theElement.getAttribute("href"); 

Getting it through getAttribute returns the actual value of the attribute, not the full version, and the href property reflects the fully functional version (for example, relative links expand).

Getting an element reference is a wide topic. If it has id , you can use getElementById . Or, if you are responding to an event, and the event occurs on an element next to the one you want, you can use various DOM properties and methods to go to it. With many modern browsers, you can use the CSS selector and querySelector (find one element) or querySelectorAll (list).

For example, this gives you the href first link on the page with the class "foo" :

 console.log(document.querySelector("a.foo").href); 

Full example: Live Copy | Live source

 <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Getting the Link</title> </head> <body> <a id="theLink" href="/relative/link">Link</a> <script> (function() { var theLink = document.getElementById("theLink"); display("<code>href</code> property: " + theLink.href); display("<code>getAttribute('href')</code>: " + theLink.getAttribute("href")); function display(msg) { var p = document.createElement('p'); p.innerHTML = String(msg); document.body.appendChild(p); } })(); </script> </body> </html> 
+9
source

The following code will iterate over all the <a/> elements and write their href value (if any):

 var anchors = document.getElementsByTagName('a'); var i, len = anchors.length; for( i = 0; i < len; i++ ) { console.log(anchors[i].getAttribute('href')); } 
0
source

Source: https://habr.com/ru/post/1489894/


All Articles