find & replace part of file path for 'src' attribute - javascript

Assuming I have a theme switcher, and there're multiple images/icons
<img src="images/icons/icon-1.png">
<img src="images/icons/icon-2.png">
<img src="images/icons/icon-3.png">
<img src="images/icons/icon-4.png">
And also I have another set of these icons with a different color/path
<img src="images/icons/blue/icon-1.png">
<img src="images/icons/blue/icon-2.png">
<img src="images/icons/blue/icon-3.png">
<img src="images/icons/blue/icon-4.png">
the below jQuery code working perfectly when I click to change theme color for 'once'
$('img').attr('src', $('img').attr('src').replace('images/icons', 'images/icons/blue'));
If I clicked again to choose another color say 'red', the path become like this
<img src="images/icons/red/blue/icon-1.png">
while it's supposed to be like this
<img src="images/icons/red/icon-1.png">
how I can make 'replace method' to find & overwrite old path WITHOUT change file name 'icon-1.png' for example, as it's a dynamic icons.
Thanks in advance.

Is the name always the same? in that case you can use the following code
$('img').attr('src', function(i, src){
return 'images/icons/blue/' + src.split("/").pop()
});

You need to loop and replace the src of each element.
$('img').attr('src', function(i, src){
return src.replace('images/icons', 'images/icons/blue')
});
When you use the getter version of .attr() it will return the attribute value of the first element in the matched element set, so the same value will get set for all elements.

Just get the filename from the source first, then rewrite the whole source. Assuming that you send as "theme" to changeTheme function, something from the following values: "images/icons", "images/icons/blue", "images/icons/red", etc. this will do the trick.
function changeTheme(theme) {
var img=$(img);
var filename=img.attr('src').split('/');
filename=filename[filename.length-1];
img.attr('src',theme+"/"+filename);
}
Or if you don't minde storing the file name as a data attribute to the image, you can change the second and third lines of the functions, with something along the lines of:
var filename=img.data("filename"); //assuming you are storing the file name in data-filename attribute

Related

I want to ask a question about javascript image src

<img src="../1.jpg" alt="" id="change-image">
<button id= "press-to-change">Press</button>
let count = 0;
let arr = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"]
document.getElementById("press-to-change").addEventListener("click", function(){
count++;
document.getElementById("change-image").src = "../" + arr[count]
So we have an HTML with an image and a button and in JS we have an array with images and we want to change the src of the image when we press the button(this is only a part of the code)
The above code works fine but i have a question why with:
document.getElementById("change-image").src = "../" + arr[count] code works fine but with document.getElementById("change-image").src = `url('../${arrImage[count]}')` code doesn't work.
For example this next code from another project works perfectly imageContainer.style.backgroundImage = `url('../${arrImage[count]}')`
background-image is a for style of an element and uses css format.
src is for the actual source of the image element and requires a valid path only
With images, you use or assign to the src property only for <img> elements.
If you want to set the background image of an arbitrary (but non-<img>) element, you need to use different syntax: you have to assign to the style.backgroundImage property, and you have to surround the URL you're setting with url(...)
The rendered HTML markup looks like this:
<img src="foobar.png">
<div style="background-image: url('foobar.png');"></div>
They're not interchangeable. With the background-image property, you need to always use url(...). With the src attribute, you need to never use url(...).
The text: url(image.jpg) is syntax only used in CSS.
That’s why it works for backgroundImage but not src
An image will always need src="path/to/image.jpg" without url() surrounding it.

change some text in src of image tag using jquery [duplicate]

This question already has answers here:
Changing the image source using jQuery
(17 answers)
Closed 4 years ago.
I want to change one letter in the src of the image tag using js or jQuery.
<img src="/media/image_i/ball.png">
<img src="/media/image_i/bat.png">
I want to change that letter i in the src to a number.
Eg.it should look like this -
<img src="/media/image_4/ball.png">
<img src="/media/image_4/bat.png">
EDIT- When i used the solutions everything was working, but it was changing the "src" of all image tags to same as first image, so the second image which is "bat.png" is getting changed to "ball.png", so same image is displaying two times.
Thank you!
You can simply get the src attribute of the images, loop it over and replace the _i with _4 using JQuery. To check the below snippet works, you need to use inspect element of the browser and check the src attribute.
$(document).ready(function(){
$('img').each(function(){
var src = $(this).attr('src');;
$(this).attr('src', src.replace('_i','_4'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/media/image_4/ball.png">
<img src="/media/image_4/bat.png">
You can do this job using regex.
$(document).ready(function(){
var src = $('img').attr('src');
var newsrc = src.replace(/_./g, '_4');
$('img').attr('src', newsrc);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/media/image_i/ball.png">
You can develop it further.
For more : https://stackoverflow.com/a/2912904/5792209
First, you'll need to identify the particular img element you need to modify. This can be done in a variety of ways, like giving the img in question an id or a class that is unique. If the image is the only one using the src you've specified in your question, you can use that (and that's what I'm doing in the code that follows).
After getting the proper reference to the element, use the .attr() method to get/set the current src value and the standard String.replace method to swap the values:
var current = $("img[src='/media/image_i/ball.png']");
current.attr("src", current.attr("src").replace("_i", "_4"));
If this is all you need to do, JQuery is overkill. Standard JavaScript is just as simple:
var el= document.querySelector("img[src='/media/image_i/ball.png']");
el.src = el.src.replace("_i", "_4");

Jquery how do we add custom attribute to <img>

I just want to add custom attribute to <img> tag which is created inside Jquery plugin....
this._image = L.DomUtil.create('img', 'leaflet-image-layer custom_image_class');
Above line creates <img> tag with the class name
`leaflet-image-layer custom_image_class`
I was able to add id attribute by adding
this._image.id = "my_image_id";
result is shown as,
<img src="" class="leaflet-image-layer custom_image_class" id="my_image_id">
everything works fine till above....
But now i want to add custom attribute "my_image" so that result should look like....
<img src="" class="leaflet-image-layer custom_image_class" id="my_image_id" my_image = "something">
how do we achive this?
I have already tried with attr , but no luck...
Note that inventing your own non-standard attributes (such as my_image) will mean that your HTML is invalid. Instead you should use data-* attributes. Try this:
this._image.dataset.my_image = "something";
Or if you want to use jQuery instead:
$(this.image).data('my_image', 'something');
use jquery attr
this._image = L.DomUtil.create('img', 'leaflet-image-layer custom_image_class');
this._image.id = "my_image_id";
$('#my_image_id').attr("my_image","something"); // add this line

Remove filepaths from multiple image elements in HTML using jQuery

I'm trying to keep the filenames but remove the filepaths from the image elements on my page, and I've managed to figure out the following based on what I've already gathered from similar questions.
I'm able to remove just the filepaths, but I can't figure out why the source of the first image is being copied into the other two images.
Here's what I've put together so far
HTML
<img src="/path/to/image.gif" />
<img src="/different/path/to/picture.jpg" />
<img src="another/path/to/graphic.png" />
JS
var abc = $('img').attr('src');
var def = abc.split('/').pop();
$('img').attr('src', def);
RESULT
<img src="image.gif">
<img src="image.gif">
<img src="image.gif">
http://jsfiddle.net/aztdeu0w/
You arent iterating through all the img elements, try the following:
$('img').each(function(){
var imgName = $(this).attr('src').split('/').pop();
$(this).attr('src', imgName);
});
That way you will loop through all the images and replace accordingly the src attribute.
This is how jQuery works. The $ selector grabs an array of items (containing 0-N matched elements) and then applies your operations to those elements. For some operations though- read operations like attr('src') it only makes sense to read a single item, so it reads the first one.
What you want is to iterative over the images and apply your regex to them one at a time. So...
$('img').each(function(index, item){
// Read/write attr here
});

jQuery to change element Attributes and return the edited Html Source back?

Actually what i'm doing is to find the <img> image tags and get its src attribute to change them.
I already got upto this point but the problem more is: To get the edited the html source back (to put into the database.)
To say more brief & clearly, i'm about to grab some Dynamic Html Containers and then change the image paths and save the whole source chunk back.
For brief example if i search inside $(div.container).html() on this:
<div class="container">
<..> .. </..>
<..>
<img src="images/apple.jpg" />
<..>
<img src="images/banana.jpg" />
</..>
</..>
</div>
Firstly, lets say <..> represent any of not previously knowable html tags.
Then i will get:
var dom_contents = $("div.container").html();
Now i got the original html source inside the target container <div>
Then lets say i need to change each <img src with sample/ for its folder. It will then be fruits/apple.jpg and fruits/banana.jpg.. etc.
I still getting some of the stuffs like:
$("div.container).each(function() {
var arr = $(this).find("img");
for (var i=0; i<arr.length; i++) {
var img_src = $(arr[i]).attr("src");
/*
* I NEED TO CHANGE THE IMAGE SRC HERE
*/
}
});
** Finally, i need to save this the whole edited html source into the database. **
So how do i change the <img src='' .. and
How do i get this whole edited html source, back from the jQuery?
Amend the source attribute for each image as follows. You don't need to write the html back. The source html will be updated:
$("div.container").each(function() {
$(this).find("img").each(function() {
$(this).attr("src", "/image/url/file.png");
});
});
To get the html source of the container, use the following:
$("div.container").html();
This will set the attribute:
$(arr[i]).attr("src", mynewsrcvalue);
Once you're done just send the innerHTML (or .html()) back in an AJAX request. But if you want this stuff in a database, why not just manipulate the source on the server side in the first place?

Categories

Resources