Find a element and append a image - javascript

I know how to append a image to a known tag. e.g.
//html
<div class="ImageContainer"></div>
//JS
var image = new Image;
image.src = '/Public/Images/image.png';
image.appendTo($('.ImageContainer'));
but how to find a certain tag(the figure tag here) and append the image?
I could locate the figure tag with '.find()':
var ImageContainer = $('<div><figure></figure></div>').
console.log(ImageContainer.find('figure').html());
but failed to append the image to it:
image.appendTo(ImageContainer.find('figure')); //doesn't work

If you have an image element with an id you can select it like so:
var $image = '<img src="/Public/Images/image.png" />';
Then so find the figure elemnt:
$(ImageContainer).find('figure').append($image);

Try below code.
1) Stored image url in variable name $img.
2) Find the div using class name 'image' ($('.image'))
3) Appended image to div
HTML
<div class="image"> </div>
JS
var $img = '<img src="https://skypeblogs.files.wordpress.com/2013/05/skype-button.png"/>';
$('.image').append($img);
JSFIDDLE DEMO

if you are using jquery, you can just do
var htmlString = '<div><figure><img src="some image src" /></figure></div>';
$('#ImageContainer').html(htmlString);
but if you are wanting to insert the div/figure and image separately, then you'd be best giving it some sort of identifier, i.e.
var htmlString = '<div><figure id="myFig"></figure></div>';
$('#ImageContainer').html(htmlString);
$('#myFig').html('<img src="" />');

Related

Using a var in an <img src> tag

I've been trying to work out my own photo album when I encountered an error. It's a syntax error but after trying out a number of different ways of writing the code it just wont work.
Here's what I did. I made a var image which contains the string file path (using string manipulation) of the image (I am not to use PHP just yet, so it can only accept photos from a given folder named "images" on the base directory) and another var imgSource to contain the actual image itself using the var image.
The code is:
var image = "images/" + $(".inputImage").val().split('\\').pop();
var imgSource = $('<img src = image alt = "Image not found" class = "card-img-top">');
for some reason, even without the apostrophes, the tag reads the word image as the filepath (string) not as variable I've created.
You would use
var imgSource = $('<img src="' + image + '" alt="Image not found" class="card-img-top">');
var image = "images/" + $(".inputImage").val().split('\\').pop();
var imgSource = $('<img src="' + image + '" alt="Image not found" class="card-img-top">');

Fetch and add img attributes to string

I have a string like this.
x = '<div class="sample">
<img src="http://www.example.com/i/java.png">
</div>
<div class="sample_another">
<img src="/i/somedir/python.png">
</div>'
I want to convert to this
x = '<div class="sample">
<img src="http://www.example.com/i/java.png" height="200px" width="100px">
</div>
<div class="sample_another">
<img src="/i/somedir/python.png" width="150px" height="150px">
</div>'
input string will be a html doc. for all the images in the doc, i want to add the height and width property. and to get the height and width property i have to use something like this
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.example.com/intl/logo.gif';
p.s. i tried using this solution but the problem i face is that the string might have the script tag and DOM parses it as a closing script tag. I cant find much for regex either. So is there any other way to obtain this result ?
Thanks.
If you can remove scripts than go with this code:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
var string ="<script type"text/javascript"></script><img alt=''
src='http://api.com/images/UID' /><br/>Some plain text<br/><a
href='http://www.google.com'>http://www.google.com</a>";
var elem= document.createElement("div");
$(string).find('script').remove();
elem.innerHTML = string;
var images = elem.getElementsByTagName("img");
for(i=0; i<images.length; i++){
images[i].width = "150";
images[i].height = "250";
}
string = elem.innerHTML;
Problem you are facing with is that it turns out that HTML5 does not allow script tags to be dynamically added using the innerHTML property. So you will need to add them dynamically on some other way.
This is some code that might help you:
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src','http://example.com/site.js');
document.head.appendChild(my_awesome_script);

accessing nextElementSibling in HTML

I have written a lightbox script in plain JS:
HTML:
<img onclick="pLightbox(this)" src="MyPhoto.jpg" />
JS:
function pLightbox(objPhoto){
var path=objPhoto.src;
HTMLtext = '<img src="' + path + '">';
containerDiv.innerHTML = HTMLtext;
}
(code abbreviated for clarity)
This works fine. Now I'm trying to access the next sibling within the DIV. I have tried:
HTMLtext += '<img src="images/Next.png" onclick="pLightbox(' + objPhoto.nextElementSibling + ')">';
This doesn't work - Tried several different variations (nextElementSibling.src, etc.) , but nothing works.
How do I access the next sibling from an HTML string?
Eh, no. Do not concatenate DOM elements with strings. Do not use event handlers. Especially, do not use event handler content attributes.
This is the proper way. No events in HTML. No nasty string manipulation. No HTML injection vulnerabilities.
document.querySelector('img').addEventListener('click', pLightbox);
function pLightbox() {
containerDiv.innerHTML = "";
var img = document.createElement('img');
img.src = this.src;
img.addEventListener('click', pLightbox.bind(this.nextElementSibling));
containerDiv.appendChild(img);
}
<img src="//stackoverflow.com/favicon.ico" />
<img src="//scifi.stackexchange.com/favicon.ico" />
<img src="//superuser.com/favicon.ico" />
<img src="//crossvalidated.com/favicon.ico" />
<div id="containerDiv">Click the first image. Then keep clicking the new image</div>

Adding onClick function in a variable a href

I'm a begginer with Javascript and I would like to know if there is a better way to write this piece of code:
var images = [],
index = 0;
images[0] = "<a href = 'link' onclick='_gaq.push(['_link', this.href]);return false;'>
<img src='image.jpg'></a>";
images[1] = "<a href = 'link1' onclick='_gaq.push(['_link', this.href]);return false;'>
<img src='image1.jpg'></a>";
index = Math.floor(Math.random() * images.length);
document.write(images[index]);
This code doens´t work, I think is because I'm including the onClick function inside the variable description...
The function would be to print randomically the images, but adding the _gaq.push parameters in the url image link.
Is there any other way the write this code?
Thanks
No need to create the html in javascript. You can do the following:
JavaScript (must be instantiated before the html is rendered):
var pushMe = function(link){
_gaq.push(['_link', link.href]);return false;
};
Html:
<a href = "link" onclick="pushMe(this);">
<img src="image.jpg"></a>

Replace Image src before append html code

I have a html content variable in js as
var htmlIs = '<p><img src="images/stories/fight_bpl.jpg" /></p>';
and I am appending it to the div using
$("#divId").append(htmlIs);
but here I just want to replace the src want to add the external image link here before append the content so how can I do this?
You can create a jQuery object:
$(htmlIs).find('img').attr('src', 'url').end().appendTo('#divId');
http://jsfiddle.net/BdnYd/
For multiple images:
var htmlIs = '<p><img src="images/stories/img_1.jpg" /><img src="images/stories/img_2.jpg" /></p>';
var urls = ['url1', 'url2']
$(htmlIs).find('img').each(function(i){
$(this).attr('src', urls[i])
}).end().appendTo('#divId');
http://jsfiddle.net/TUFcX/

Categories

Resources