How to get an image HTML which parent has more children? - javascript

I want to get the whole HTML tag of an image (<img src="url" ... />). I can do it with .html() function if I refer to its parent:
<div id="image">
<img src="url" />
</div>
and with JQuery:
$('#image').html()
But how could I do it if I don't have an image "only" parent:
<div id="image">
<img src="url" />
<!-- Here some stuff. E.g. -->
<div><p>Something</p></div>
</div>
If I do $('#image').html() here, I'll get the whole content. If I do $('#image img').html() I'll get an empty string.
How could I get the whole <img> tag here?

You can use .outerHTML
$('#image img').prop('outerHTML')
$('#image img')[0].outerHTML //in this case you need to test whether $('#image img')[0] exists
Demo: Fiddle

In Javascript, it's as simple as:
document.getElementById('image').getElementsByTagName('img')[0].outerHTML
and as cookie monster says,
A nice alternative if IE6/7 support isn't needed would be document.querySelector("#image > img").outerHMTL
DEMO

Related

How do I replace only part of an image source?

Is there a way to use jQuery to change a part of an image's source URL?
I'm working on a page that has a number of image elements that are all programmatically generated (but I'm not able to access the source code that generates them). And they all share the same class.
Let's say I have the following HTML:
<img src="https://cdn.example.com/pictures/01.jpg" class="photo">
<img src="https://cdn.example.com/pictures/02.jpg" class="photo">
<img src="https://cdn.example.com/pictures/03.jpg" class="photo">
<img src="https://cdn.example.com/pictures/04.jpg" class="photo">
Simple enough. But now, what if I want to point them all to a different directory? Like: /images/
So far, I've tried a few things, including this bit of jQuery, but nothing's done the trick so far:
$("img.photo").attr("src").replace("pictures","images");
That feels like it should do it because it's targeting images with that class -> then the "src" attribute -> and telling it to replace "pictures" with "images."
But I'm extremely new to using jQuery, so I'd appreciate some help.
What am I missing here? Any advice?
UPDATE: Huge thanks to those who provided answers and explanations — I really appreciate you helping a beginner!
In your code you simply change the returned string from
$("img.photo").attr("src") without doing anything with it afterwards. This will not change the attribute in your <img> elements.
This should do the job:
$("img.photo").each(function(){this.src=this.src.replace("pictures","images")})
Here I go through all the matched elements and assign the changed src string back to each element's srcattribute.
$("img.photo").each(function(){this.src=this.src.replace("pictures","images")});
// list the changed src values in the console:
console.log($("img.photo").map((i,img)=>img.src).get())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://cdn.example.com/pictures/01.jpg" class="photo">
<img src="https://cdn.example.com/pictures/02.jpg" class="photo">
<img src="https://cdn.example.com/pictures/03.jpg" class="photo">
<img src="https://cdn.example.com/pictures/04.jpg" class="photo">
Your code snippet won't work, because that's grabbing the src attribute of the first image, and changing it, but never setting the result as the new src on the <img> elements.
Try this
$("img.photo").each((index, img) => {
img.src = img.src.replace("pictures","images");
});

retrieve contents of div and make image src

Is there a way to fetch the content of a div and place that ocntent in the 'src' parameter of an image? I'm working on a project that uses json to load translation files, and tehrefore I can't load an image directly, but figured I could at least load the image name.
So:
<div id="flag-name" style="hidden">en-flag.jpg</div>
<img src="DIV CONTENTS HERE">
Ideas appreciated! (Am also using jquery so open to that as well)
The button demonstrates that ablility. Use the button's onclick code wherever you need.
<div id="flag-name" style="hidden">en-flag.jpg</div>
<img id="myImage" />
<button onclick="document.getElementById('myImage').src=document.getElementById('flag-name').innerText">Change</button>
You can simply do it in jQuery by getting the text of the div and then setting the source of image like this:
var source = $("#flag-name").text();
console.log("before - " + $("#image").attr("src"));
$("#image").attr("src",source);
console.log("after - " + $("#image").attr("src"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="flag-name" style="hidden">en-flag.jpg</div>
<img id="image" src="DIV CONTENTS HERE">
You need an event to start the jQuery/javascript -- so I added a button. Also, you will find it easier to target specific DIV and IMG tags if you give them IDs or classes.
$('button').click(function(){
var mySrc = $('#flag-name').text();
$('img').attr('src', mySrc);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="flag-name" style="hidden">http://placeimg.com/300/200/animals</div>
<img src="DIV CONTENTS HERE">
<button>Go</button>

How to change image src using jQuery

<div class="branding">
<h1 class="logo">
<a href="http://www.whatever.com/" class="logo">
<img src="http://www.whatever.com/test.png"></a>
</h1>
</div>
I am trying to access the image src with the following to no avail:
$("a.logo img").html("<img src='http://www.whatever.com/newimage.png'>");
The reason I am doing this is because the image is on a third party that I can't access the codebase to make the change so I am trying to rip out their with my code.
src is attribute. You should use .attr() to get/set attribute values using jquery:
$("a.logo img").attr("src","http://www.whatever.com/newimage.png");
.html() changes the html CONTENT of a node, e.g.
orig: <p>foo</p>
$('p').html('bar');
neW: <p>bar</p>
An <img> has NO content. Try
$('p.logo img').attr('src', 'new url here');
Did you try
img.attr('src','http://mynewsource.com');
I figured out the answer:
$('a.logo img').attr("src", "http://www.whatever.com/newimage.png" );
Thanks!

Using jQuery to read img src and insert img src dynamically

I have some code on my page that looks like this:
<div class="img-center">
<img src="img-path.jpg" alt="alt-text" class="feature-image" />
</div>
I am setting up a Print Stylesheet and due to some javascript manipulation of the content (and possibly a bug in firefox) the img prints off center. The solution I am going to do is have the img inserted dynamically into another div that will show when printed but I do not know how to have jQuery read the img div and then copy it into the other div. The code example for the other div would be something like this:
<div id="feature-container-print">
<img src="jQuery inserted copy of above img-path.jpg" alt="alt-text" />
</div>
How is this done? Please provide an example.
$('#feature-container-print img').attr('src',$('.feature-image').attr('src'));
I believe this would work:
$('.feature-container-print img').attr('src', $('.img-center img').attr('src'));
$('.img-center img').hide();
$('.feature-container-print img').show();

Replace URL parameter values in links using JavaScript/jQuery?

My CMS's lightbox-style photo gallery outputs code like below. I've provided code for two thumbnails.
The parameter values for "m" and "s" will always be "150" and "true." I'd like to change that to m=250 and s=false.
I'm new to JavaScript and jQuery. If you have a suggestion, please help me out with where to put the code on the page. Thank you.
<div class="thumbTight MainContent">
<div class="thumbContents">
<a href="/PhotoGallery/banana.jpg" rel="lightbox[2065379]" title="Banana">
<img src="/ResizeImage.aspx?img=/PhotoGallery/banana.jpg&m=150&s=true" alt="Banana" />
</a>
<div class="description" style="display: none;"></div>
</div>
</div>
<div class="thumbTight">
<div class="thumbContents">
<a href="/PhotoGallery/cantaloupe.jpg" rel="lightbox[2065379]" title="Cantaloupe">
<img src="/ResizeImage.aspx?img=/PhotoGallery/cantaloupe.jpg&m=150&s=true" alt="Cantaloupe" />
</a>
<div class="description" style="display: none;"></div>
</div>
</div>
In your document ready handler, use each to iterate over the thumbnails (images inside divs with the thumbContents class) and assign the src attribute to the original src attribute with the required substitutions.
$(function() {
$('.thumbContents img').each( function() {
var $img = $(this);
$img.attr('src', $img.attr('src').replace(/m=150/,'m=250').replace(/s=true/,'s=false') );
});
});
You can run this jQuery after the page has loaded. The images will start loading with the different URL, your code will run and change the image URLs and then the new one will load and display. There is nothing you can do client-side to prevent the initial display unless you actually use CSS such that they images are initially hidden and only made visible AFTER you've set the desired URL.
$(".thumbTight img").each(function() {
this.src = this.src.replace(/m=150/, "m=250").replace(/s=true/, "s=false");
});
You can see a demo here: http://jsfiddle.net/jfriend00/UdnFE/.

Categories

Resources