Gari BN
Gari BN

Reputation: 1685

Get the raw value of href and src attributes in javascript

Given an HTML element, I'd like to get the raw value of its src attribute using Javascript.

If the src value is relative path, element.src returns an absolute path.

For example:

  1. //ssss.com ==> http(s)://ssss.com

  2. blabla ==> http(s)://ssss.com/path/blabla

I know that it is possible to get the HTML code as string and to filter it, but this is not efficient.

I'm looking for efficient and clean way to extract the raw value of src/href attributes, given the HTML element with the attribute.

Thanks!

Upvotes: 3

Views: 1068

Answers (2)

BenM
BenM

Reputation: 53198

You're confusing object properties with attribute values. What's wrong with just using getAttribute()?

var element = document.getElementById('test');

console.log( element.href );
console.log( element.getAttribute('href') );
<a href="test.html" id="test">Testy</a>

Notice that element.href is parsed by the browser, whereas getAttribute() returns the raw string that was specified in the DOM. You can also similarly use getAttribute('src') for <img /> elements.

For completeness, this is the same behaviour that is demonstrated in jQuery. Most developers will use them synonymously, but they're actually subtly different.

For example:

console.log( $('#test').prop('href') );
console.log( $('#test').attr('href') );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="test.html" id="test">Testy</a>

Notice how prop() behaves in the same way as element.href, and attr() is identical to getAttribute().

Upvotes: 6

Jeremy Thille
Jeremy Thille

Reputation: 26370

Try with .getAttribute()

const src = document.getElementById("test").getAttribute("src")

console.log(src) // logs "/source"
<img id="test" src="/source"/>

Upvotes: 1

Related Questions