Cannot append image with jquery - javascript

I currently have a code working where i can add a class based on the url of a page using jquery. However I would like add an image to a div instead of just adding a class. I'm not as proficient in java-script as I could be but I think there is probably a pretty simple solution. The code that doesn't work is
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var img = document.createElement("img");
img.src = '~/Content/Images/Template 5A Filmstrip.jpg" />';
}
the code that works right now that I dont want to use is
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var $body = $('body');
$body.addClass('campaign');
}
How can apply what I do know that works to what I am trying to get to work?

If for some reason you don't want to use jQuery for this part, you just need to append the element to the body of the html document (or wherever you want it to end up) like so:
Javascript Code
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var body = document.getElementsByTagName("BODY")[0];
var img = document.createElement("img");
img.className = 'img-responsive'
img.src = '~/Content/Images/Template 5A Filmstrip.jpg';
body.appendChild(img);
}

You can add a <img> to any element using the jQuery .append() function in the following way:
var imageToAppend = '<img src="http://example.com/img.png" height="200" width="200"/>';
$('#myElementId').append(imageToAppend); //This will append you HTML to the div with id "myElementId"
You can read more about this here: http://api.jquery.com/append/
Happy coding! =]

You should use the element where you need to append (prepend) the image element so the code will look something like:
$("base element selector").append(img);
but you need to consider that the address of the image source may not be correct from the browser point of view - consider the page is hosted in application like http://server.com//applicationgroup/applicationroot/Content/Images/.....jpg may not be pointed with ~/Content/Images/.....jpg you rather need to translate the address to the full server address on the server side.

In my case I just had to remove "~" from:
<img src="~/assets/icons/ic_chevron2.svg" class="rot-90" />
resulting in:
<img src="/assets/icons/ic_chevron2.svg" class="rot-90" />

Related

Variable attributes disapearing when put inside div

Probably a simple question but I can't seem to find the answer. I am dynamically creating a page where I can share twitter links.
var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('data-text', 'I liked this image');
etc..
I then append it to the div I want such as
$('#doc').append('<img(miscellaneous HTML)>'+twitter)
What I have above works but for CSS formatting purposes I want the image with the twitter share button to be a sub-block. So I create something like this
$('#doc').append('<div id="innerblock'+i+'"><img(miscellaneous HTML)>'+twitter+'</div>)
But when I do this it seems all the attributes of the twitter var are lost, only printing http: // twitter.com/share on the page instead of the button.
I feel it's probably a basic concept I am forgetting.
You are tring to concatenate a DOM object and a String via this code
$('#doc').append('<div id="innerblock'+i+'"><img(miscellaneous HTML)>'+twitter+'</div>)
This twitter variable contains a DOM object and the rest of the append block is String.
Try this:
var div = $('<div id="innerblock'+i+'"><img(miscellaneous HTML)></div>').append(twitter);
$('#doc').append(div);
What I would do is instead of appending the HTML instead you can create the innerblock div and the img tags using document.createElement and append the twitter to the img and the img to the div before appending it all to #doc
You can not concatenate a sting and a DOM node.
var div = $("<div id="innerblock'+i+'">").append("<img />").append(twitter);
or
var div = $("<div/>", {id : "innerblock" + i).append("<img />").append(twitter);
Try substituting .outerHTML String of twitter for DOM element Object twitter ; also adding closing sing quote ' at end of string parameter provided to .append()
var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('data-text', 'I liked this image');
var i = 0;
$('#doc').append('<div id="innerblock'+i+'"><img />'+twitter.outerHTML+'link</div>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="doc"></div>

remove html tag using jquery/javascript

I have an html element on my website that is being put there beyond my control and I need to remove it using javascript/jquery. The HTML tag is consistent and on every page, it looks like this:
<img src="https://myimage.com/myimage.jpg" style="cursor:pointer;border:none;">
how do I remove it? The image has no ID. Thanks so much in advance!
You can remove it like this:
jQuery("img[src='https://myimage.com/myimage.jpg']").remove();
Be sure that that code is in a script tag below the relevant image in the markup of the page. If the image is being added dynamically after the page markup has been parsed, you may have to be more crafty:
(function() {
function removeImage() {
var img = jQuery("img[src='https://myimage.com/myimage.jpg']");
if (img.length) {
// It's there now, remove it
img.remove();
}
else {
// Not there yet, check again in a quarter of a second
setTimeout(removeImage, 250);
}
}
removeImage(); // Start the process
})();
Note: You're removing an element, not a tag. Tags are markup (text). Elements are the result of tags being parsed and created by the browser.
use
$("img[src='https://myimage.com/myimage.jpg']").remove();
That will hide that image
Here you go
$("img[src='https://www.google.com/images/srpr/logo11w.png']").remove();
http://jsfiddle.net/bowenac/GD64n/
Mind explaining what the image is or post a live link? This will remove it from displaying but will not fix the source of the problem if this is some kind of hack placing this code into your files...
No jQuery, plain JS:
var img = document.querySelector('img[src="https://myimage.com/myimage.jpg"]');
if (img) {
img.parentNode.removeChild(img);
}

Adding a Values into a div created from document.createElement

I have a DIV that is created from document.createElement,, I have a few text and a image that needs to be added to this DIV. Could some one suggest me the best way to do it? The image path is given in the image variable. Below is the code that i have already written. contentattachpoint is another DIV that is there in the HTML page which is got by
var contentattachpoint=document.querySelector('.contentattachPoint');
var year="Year of Manufacture:"+arr[i].year;
var power="Engine Power:"+arr[i].power;
var description="Description:"+arr[i].description;
var image=arr[i].image;
var details = document.createElement("div");
details.setAttribute("id", "details");
details.className = "details";
details.value=year+power+description;
contentattachpoint.appendChild(details)
Thanks in advance.
By what I understand of you question I consider that you need text and image both in the div that you created so do something like this
details.innerHTML = description + "<img src='"+image+"'>";
just do what you are already doing use details.appendChild()
Look at this sample example:
just created a demo example to show you how to dynamically create a div and add paragraph tag and image tag to it.
http://jsfiddle.net/2LAYS/2/
If you are using jQuery, use the .append() function.
Example:
$('#details').append('<img src="' + image + '" />');
you should also take a look at Prepend
Source(s)
jQuery API - append()
jQuery API - prepend()

Get src of img element from div?

I want to get the src of the img element in HTML. It looks like this:
<div class="image_wrapper" id="this_one">
<img src="Images/something.jpg" />
</div>
It's very simple when I put an ID in img, and get this src very easy.
But the problem is when I get src of img from div element.
var someimage = document.getElementById('this_one').firstChild.getAttribute("src");
alert(someimage);
I need to get this URL in string. But not worth.
Why not try something like this:
var someimage = document.getElementById('this_one');
var myimg = someimage.getElementsByTagName('img')[0];
var mysrc = myimg.src;
For more on using getElementsByTagName you may want to look at:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
There is some error checking I didn't do here, but I am just trying to show how you can do it.
Or even simpler :
document.getElementById('yourimageID').getElementsByTagName('img')[0].src
Works for me
The problem is that you have the space characters between the div and img tags. That is why the first element of the div is not the image but the text - which has no method getAttribute.
You can remove spaces and use your js as it was:
<div class="image_wrapper" id="this_one"><img src="Images/something.jpg" /></div>
it will be working:
var someimage = document.getElementById('this_one').firstChild.getAttribute("src");
alert(someimage);
You can get the image tag from your's div using getElementsByTagName('img') as following:
var divEl = document.getElementById('this_one'),
src = divEl.getElementsByTagName('img')[0].src;
The above will solve your task.
More you can get from here Scripting Documents, I advise you to read this chapter.
I know the question is asked for js which has been answered, for jquery
var image = $('#this_one img')[0]; // $('#this_one img') this will return the img array. In order to get the first item use [0]
var imageSrc = image.src;
alert(imageSrc);
It might be useful for someone who looks similarly in jquery.
First, instead of using element.firstChild , use element.children[0] . Also, instead of element.getAttribute('src') , use element.src .
Hope this helps,
Awesomeness01
Why do we need to use jQuery if we can get the img src within the document by querySelector?
Try this:
document.querySelector('[src*="Images/something.jpg"]')
P.S.: jQuery has 94 kb minified file size. Please don't include it unless there's a requirement.

How to change a website image with javascript? [duplicate]

I'm working with my first Greasemonkey script.
And its for a website that have a logo, i want to change the image to a image i have created, and i wonder how i do this?
like use JavaScript to edit the current html document and replace the image.
Thanks for any help!
Edit: The image is inside a <img> tag, the image i want to change/replace is in this code:
<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo" width="170" height="36">
Here is the javascript code i tryed and didnt work:
var myImage = document.querySelector('.fb_logo img');
myImage.src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
var logos = document.getElementsByClassName("fb_logo");
for( var i = 0; i < logos.length; i++ )
{
// true for all img tags with the fb_logo class name
if( logos[ i ].tagName == "IMG" )
{
logos[ i ].src = "http://www.computerweekly.com/blogs/it-downtime-blog/lolcat-tan.jpg"
}
}
Knowing that you can use browser-specific javascript is a plus.
Use querySelectorAll.
var img = document.querySelectorAll('.yourClass')[0];
Note: you're possibly selecting more than one element, so it's returning a nodelist rather than a single node, remember to select the first item in the list.
Better yet, use querySelector
var img = document.querySelector('.yourClass');
Okay, here's a complete Greasemonkey script that swaps the logo image at Facebook under real-world conditions (meaning that the image may be in different places and you have to deal with the container and background images, etc.).
Note that this script looks for the image in two types of locations, and deals with the surrounding HTML, and CSS, if necessary.
Also note that it uses jQuery -- which is a godsend for writing GM scripts.
Finally: note that I avoid Facebook, and only know of the one logo location (plus the one that the OP reports. If there are new/different locations, deal with them in a similar manner.
// ==UserScript==
// #name _Facebook Logo Swap
// #include http://www.facebook.com/*
// #include https://www.facebook.com/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
/*--- Found FB logo at:
"h1#pageLogo a" as a backgound image.
It's reportedly also at: "img.fb_logo.img"
*/
var desiredImage = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
//--- Straight image swap:
$('img.fb_logo').attr ('src', desiredImage);
/*--- Replace the link's -- with the logo as a background -- contents with just a plain image.
Since this image is transparent, clear the old BG image.
Also constrain the new img to its container.
*/
$('#pageLogo a').css ('background-image', 'none')
.append ('<img>').find ('img') .attr ('src', desiredImage)
.css ( {width: '100%', height: '100%'} );
find the image tag and replace the src attribute.
var myImage = document.getElementById(idOfImageYouNeedToChange);
myImage.src = "your_image";
Pretty straightforward.
You can do this very simply with jQuery
$('.fb_logo').attr('src','newimage.jpg');
you have to get the reference to your img element first, better use id instead of a class, since getElementsByClassName is not supported in IE until ie9:
with raw javascript (there are many ways of doing this. this is just the one):
var theImg = document.getElementById('imageId');
theImg.src = 'someNewPath'
with something like jQuery(js library) - you can easily select by class or by id or by tag etc:
$('.yourPicClass').attr('src', 'someNewPath')
How about using the DOM to find that specific attribute and change it to whatever?
<html>
<body>
<img class="fb_logo img" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
var yerImg = document.getElementsByTagName("img");
yerImg[0].setAttribute("src", "http://goo.gl/JP8bQ");
</script>
</html>
querySelector:
return the first matching Element node within the node’s subtrees. If there is no such node, the method must return null.
querySelectorAll:
return a NodeList containing all of the matching Element nodes within the node’s subtrees, in document order. If there are no such nodes, the method must return an empty NodeList.
The Use :
var element = baseElement.querySelector(selectors);
var elementList = baseElement.querySelectorAll(selectors);
Sample :
<html>
<body>
<img class="fb_logo" src="https://s-static.ak.facebook.com/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png" alt="Facebook logo">
</body>
<script type="text/javascript">
var myImageList = document.querySelectorAll('.fb_logo');
myImageList[0].src = "http://happylifeinnyc.com/wp-content/uploads/2011/07/facebook_love_heart.png";
</script>
</html>

Categories

Resources