Amanda
Amanda

Reputation: 2143

How to know if the image path is relative?

In the following snippet, if I try to get the src using javascript

<img src="/assets/images/star.png" />

as

document.querySelectorAll("img").forEach(item => console.log(item.src))

It prints the src as http://site-name-on-browser/assets/images/start.png

Is there a way I could know if the image path is relative or not? Here while iterating I would never know this.

I was trying this :

if (img.src.match(/^\//)) {
     console.log("path is relative");
}

But this does not work since the browser returns the complete path even if the source code as the relative path.

Upvotes: 1

Views: 154

Answers (1)

Max Lysenko
Max Lysenko

Reputation: 341

You can use getAttribute() to get the value of the element's attribute.

document.querySelectorAll("img").forEach(item => console.log(item.getAttribute("src")))

Upvotes: 3

Related Questions