DOM create object direct from his HTML code - javascript

in my project i have stored in a variable (htmlG) an html code like this:
<img src="http://mygrtew.imm.com/graph?&o=f&c=1&y=q&b=ffffff&n=666666&w=450&h=250&r=1m&u=www.test.com" width="450" height="250"/>
and i would like to insert dinamically in a div that i create with DOM this image directly
var htmlG = response.testg;
var divAgraph = createElement('div', 'divAgraph', 'divAgraphcss');
var oImgG = createElement('img');
oImgG.setAttribute('src',htmlG);
divAgraph.appendChild(oImgG);
but fail, probably because in var htmlG at the beginning there is correct?
How can icreate my img with these parameters?
thanks in advance

Hope this helps:
var htmlG = response.testg;
var divAgraph = document.createElement('div');
divAgraph.innerHTML = htmlG
I assume you are working in an environment that provides DOM. (node.js does not)

You try to set the src attribute of your <img> element
oImgG.setAttribute('src',htmlG);
yet htmlG does not contain the src attribute content but a complete HTML img element as well.
So instead of your current
var htmlG = '<img src="http://mygrtew.imm.com/graph?&o=f&c=1&y=q&b=ffffff&n=666666&w=450&h=250&r=1m&u=www.test.com" width="450" height="250"/>';
oImgG.setAttribute('src', htmlG);
you probably want to
var htmlG = 'http://mygrtew.imm.com/graph?&o=f&c=1&y=q&b=ffffff&n=666666&w=450&h=250&r=1m&u=www.test.com';
oImgG.setAttribute('src', htmlG);
If you want to set the width and height attributes as well, you will have to call setAttribute for those two separately.
If you have to work with the entire HTML code for the element - as the dereferencing of response.testg suggests, you can use innerHTML to set the content of your div - and not call setAttribute at all.
divAgraph.innerHTML = htmlG

Related

How to get a the url of an image from id in Javascript

I know it's such a beginner thing. So I have this image in a div with the id thumb.
<img id="thumb" src="https://url-to-a-image">
And this Javascript that it's a magnify script:
<script type="text/javascript">
var myImgSrc = document.getElementById("thumb").getElementsByTagName("img")
[0].src;
var evt = new Event(),
m = new Magnifier(evt);
m.attach({
thumb: '#thumb',
large: 'myImgSrc',
largeWrapper: 'preview'
});
</script>
As you can see I'm trying to get the image using myImgSrc and then I'm trying to use in the large: 'myImgSrc'. When I put the a fixed url in large: fixed-url-to-the-image, it works fine.
The element with #thumb id is the tag img it self, the current selector will not return the src value, so it should be simply:
var myImgSrc = document.getElementById("thumb").src;
You can get image src like this,
var thumb = document.getElementById("thumb").src;
You don't need to use getElementsByTagName.
let img = document.querySelector('#thumb');
console.log(img.src);
If you use img.src, you'll see the source of your img tag.
getElementsByTagName is superfluous - you already have the exact element you want - you selected it by its ID. You'd only need getElementsByTagName if you wanted to get one or more elements by their tag and work on them all, rather than identifying one precisely.
So actually the solution is very simple - just get the src attribute of the ID-selected element directly. Working demo:
var myImgSrc = document.getElementById("thumb").src;
console.log(myImgSrc);
<img id="thumb" src="https://url-to-a-image">

Cannot append image with jquery

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" />

change name of DIV width JavaScript

I am using following code:
...
<div id="divcontainer1">
...
<div id="divcontainer2">
...
</div>
</div>
...
Now, I want change "divcontainer2" at a later point of time in the Div "divcontainer3".
What is the right way to check is exist divcontainer2 and when true,
change in divcontainer2 width javascript ?
Thank you,
Hardy
It is probably not nest practice but you can do this by changing the .outterHTML of the element. You would likely want to improve on this but here is a quick example. The last line checks if div 2 exists.
var div2 = document.getElementById("div2");
var html = div2.outerHTML;
var idx = html.indexOf(">");
var newtag = html.substring(0, idx).replace("div2", "div3");
div2.outerHTML = newtag + html.substring(idx, html.length - 1);
var contents = document.getElementById("div3").innerHTML;
alert(document.getElementById("div2") != undefined);
All you do is
get the element .outterHTML
get the substring representing the tag.
Replace the text that defines it
Set the .outterHTML tag to our new string
Now you have a newly named div that keeps all of its attributes, position in the parent and content.
The alert line is how you check for the existence of an object.
I don't believe that there is a "proper" way to do this, however I would store the contents of divcontainer2 in a variable, and then do something like this
var containerOfDivContainer2 = document.getElementById("containerofdiv2");
containerOfDivContaier2.innerHTML = "<div id='divcontainer3'>"/* insert div contents */+"</div>";
Of course, this requires you to put divcontainer2 in a div called containerofdiv2 but it works.
If using jQuery, this will do it:
$('#divcontainer2').attr('id','divcontainer3');
But you shouldn't be changing IDs. Use classes instead and then use the jQuery's toggleClass() function, like:
<div id="divcontainer1">
...
<div id="divcontainer2" class="style1">
...
</div>
$('#divcontainer2').toggleClass("style1 style2");

Get an attributes value of the ALT attribute of a hyperlink

My a-tag (link) contains innerHTML which is an image like this:
.innerHTML = <img alt="hello world" src="/Content/Images/test.png">
How can I get the text of the alt attribute with JQuery?
You really don't need jQuery. If you have the a element you can do this:
// lets call the anchor tag `link`
var alt = link.getElementsByTagName('img')[0].alt; // assuming a single image tag
Remember attributes map to properties (most), and unless the property is changed, or the attribute, the two should reflect the same data (there are edge cases to this, but they can be handled case-by-case).
If you truly do need the attribute there is
var alt = link.getElementsByTagName('img')[0].getAttribute('alt');
Last scenario is if you only have the image tag as a string.
var str = '<img alt="hello world" src="/Content/Images/test.png">';
var tmp = document.createElement('div');
tmp.innerHTML = str;
var alt = tmp.getElementsByTagName('img')[0].alt;
If you must use jQuery (or just prefer it) then the other answer provided by Alexander and Ashivard will work.
Note: My answer was provided for completeness and more options. I realize the OP asked for jQuery solution and not native js.
Being $a your <a/> element.
Using jQuery you can do:
$("img", $a).first().attr("alt");
Or, using pure JavaScript:
var $img = $a.getElementsByTagName("img")[0];
console.log($img.alt);
​
See it here.
use this.
var altName=$('a img').attr('alt');

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.

Categories

Resources