using absolute URLs for image source in JavaScript

How can I output the absolute URLs of images in a browser window (e.g., 'www.mysite.com/hello/mypic.jpg')? Below is a snippet of my code:

$('img').each(function() {
        var pageInfo = {};

        var img_src = $(this).attr('src');

        alert(img_src);
});

Despite trying $(this).src, my alerts only show relative URLs (e.g., '/hello/mypic.jpg') and when using it, img_src is always undefined. Is there a workaround to retrieve the absolute URL instead?

Answer №1

For those utilizing jquery, the code below should suffice:

$("img").each(function() {
  var src = this.src;
  console.log(src); // This will display the absolute URL considering the current domain
});

Answer №2

Give this a shot by directly accessing the .src property on the <img>,

$('img').each(function() {
    var imageInfo = {};
    alert( $(this)[0].src ); // You'll see the desired result here
    alert(img_src);
});

Take a look at this

Answer №3

It's important to verify the src attribute of your image tag, as it seems to be showing the complete URL in my case with this example:

<img src="www.mysite.com/hello/mypic.jpg"></img>

$('img').each(function() {
        var imgInfo = {};
        var imageSrc = $(this).attr('src');
        alert(imageSrc);
});

Check out the working example here

The src of your image should only include /hello/mypic.jpg

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: The context object is not iterable. Please note that it must be iterable in order to avoid

While going through a React course on Context API, I encountered an error that says "context is not iterable TypeError: context is not iterable". Has there been any new syntax introduced? If so, please let me know. Here is the content of app.js: I'v ...

Why won't both routes for Sequelize model querying work simultaneously?

Currently, I am experimenting with different routes in Express while utilizing Sequelize to create my models. I have established two models that function independently of one another. However, I am aiming to have them both operational simultaneously. A sea ...

What is the method for extracting input from a paragraph in Laravel?

<div class="form-group"> <label for="amount_due" class="col-sm-4 control-label">{{trans('sale.amount_due')}}</label> <div class="col-sm-8"> <p class="form-control-static">Unique text to be added ...

Retrieve all documents from a Firebase User's collection

Recently, I created a Firebase cloud function where my goal is to access every user's internal collection named 'numbers' and examine each document within that collection for some comparisons. Do you have any insights on how I can achieve t ...

Including a personalized User-Agent string in my headers for fetch requests

Currently, I am utilizing the fetch API within my React project to retrieve data from a JSON endpoint. One requirement I have is to include a custom User-Agent string in my requests. Upon inspecting my requests, I noticed that the UA string displays as: ...

Chokidar operates smoothly from the command line, but fails to function properly when invoked through the use of 'npm run'

I've implemented a script that monitors Tailwind CSS files using Chokidar. The script works perfectly when I execute the command in the CLI using chokidar 'tailwind.config.js' --initial=true -c 'npm run build-tailwind'. It successf ...

Detailed enrollment procedure

I am facing an issue with the code in my HTML that validates input types. The system detects empty fields and prevents proceeding to the next step. How can I disable this validation as some of the fields are not required? For instance, the input type < ...

Secure login verification coupled with intuitive navigation features

Just starting out with react native and I've created a UI for a restaurant app. Now I'm working on converting all static components to dynamic ones. My first task is figuring out how to implement login authentication and then navigate to a specif ...

Using jQuery to locate a JavaScript variable is a common practice in web development

I recently created a JSFiddle with buttons. As part of my journey to learn jQuery, I have been converting old JavaScript fiddles into jQuery implementations. However, I seem to be facing a challenge when it comes to converting the way JavaScript fetches an ...

Creating a dynamic word cloud in D3: Learn how to automatically adjust font sizes to prevent overflow and scale words to fit any screen size

I am currently utilizing Jason Davies' d3-cloud.js to create my word cloud, you can view it here 1. I'm encountering an issue where the words run out of space when the initial window size is too small. To address this, I have a function that cal ...

Refreshing div content on selection change using PHP ajax with Jquery

Here is my code for the portfolio.php file <select name="portfolio" id="portfolio_dropdown" class="service-dropdown"> <?php foreach($years as $year){ ?> <option value="<?php echo $year[&apo ...

Best event for Angular directive to bind on image onload

I'm currently working on incorporating this particular jQuery plugin into my Ionic application. Although I have a good grasp of creating an Angular directive to encapsulate the plugin, I am encountering difficulties in successfully implementing it. B ...

Tips for utilizing the 'contains' feature within web elements with Java Selenium WebDriver?

In my current project, I am facing a challenge with two specific elements: one is a string formatted as ABC £12,56 and the other is a box called "Cashbox" that should be 15% of the value of the string. However, when attempting to locate the CSS for both e ...

Node error connecting to Mongo database

Having trouble connecting my node server to MongoDB, here is the code snippet I am using: var http = require("http"); var url = require("url"); var Router = require('node-simple-router'); var router = Router(); var qs = require('querystring ...

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

Combining the powers of $.get and $.ready

Basically, I am facing an issue with my ajax call where sometimes it completes before the page is fully loaded. I attempted to use $( fn ) to wrap the callback function, but unfortunately, the callback does not trigger if the page is already loaded. Does a ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

Using AJAX to dynamically update content via HTTP requests

Why do I keep seeing "loading..." instead of the content from data.php? xmlhttp = new XMLHttpRequest(); function fetchData () { xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState = 4 && xmlhttp.status == 20 ...

What could be the reason for my ajax request coming back with no data?

When I make this ajax request: $.ajax({ type: "POST", url: "/admin/RoutingIndicators/Add", data: { newSecondaryRI: newRi }, success: function () { alert('hit'); document.location.reload(true); }, error: fu ...

Instead of using a computed getter/setter, make use of mapState and mapMutations to simplify

Currently, I am syncing a computed value to a component and using a computed setter when it syncs back from the component. I'm wondering if there is a more concise way to replace a computed getter/setter with mapState and mapMutations. How can this b ...