Get an attributes value of the ALT attribute of a hyperlink - javascript

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');

Related

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

DOM create object direct from his HTML code

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

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.

.innerHTML vs. createElement() | setAttribute() vs. Direct*

I was told this was not "proper", I did not worry about it until I started getting a run-time error in IE9. Here is the code I need converted to use object properties.
Why is innerHTML not considered best practice?
var c=document.createElement('div');
c.innerHTML= '<a name="a1" class="b" href="' + d[2].value + '">' + d[1].value + '</a>';
It's strange that you're putting an A element inside an A element but the below should work.
var c=document.createElement('a');
c.name = "a1";
c.className = "b";
c.href = d[2].value;
c.appendChild(document.createTextNode(d[1].value));
This assumes that d[1].value is not known to be well formed HTML from a trusted source so it is likely to be more robust against XSS than the innerHTML code.
innerHTML is perfectly fine, you are just not using it correctly.
innerHTML targets the content of a tag. meaning what's between <a> and </a>
you need to set your d[2].value with setAttribute and only d[1].value with innerHTML
this should be fine (untested)
var c=document.createElement('a');
c.setAttribute("href",d[2].value);
c.setAttribute("name","a1");
c.setAttribute("class","b");
c.innerHTML = d[1].value;
check these references and examples for setAttribute (method) and innerHTML (property)
It looks like you are creating an anchor - by using document.createElement('a') - and then creating another anchor within it. So, basically your HTML is going to look like this:
<a>
Click Here
</a>
This is not right. This is the reason why using innerHTML for anchors is not good. I think you should do it as follows:
c.setAttribute('class', 'signature');
c.setAttribute('href', 'xyz');
and so on.
You can also set the href and other attributes directly on the anchor using javascript. See http://www.w3schools.com/jsref/dom_obj_anchor.asp (Anchor object properties).

Javascript: replace a string in element.src attribute

Hi I am currently trying to replace a query string value in a a link's src attribute.
it works fine in firefox but not in ie.
example:
<a id="link" href="#" src="http://somedomain.com?id=123&size=20">link</a>
then on my js it looks kinda like this:
var link = document.getElementById('link');
link.src.replace('size=20', 'size=45');
in ie, it returns something like src is not an object error;
anyone kind enough to lend a hand?
also, i need this to be on native javascript so please don't suggest a framework as a solution thanks.
To get it to work in IE you're going to need to use link.setAttribute('src', ...).
use:
var link = document.getElementById('link');
var src = link.getAttribute("src").replace('size=20', 'size=45');
link.setAttribute("src", src);
Well, links (anchor elements) don't have a src attribute, I think that you want to change the href attribute:
var link = document.getElementById('link');
link.href = link.href.replace('size=20', 'size=45');
In your case the "src" attribute in your link is an expando attribute, since an anchor tag does not have a src.
When working with expando attributes, it's safest to set and get the values using the setAttribute('attributeName',***value*)** and getAttribute('attributeName') accessors.
To find out more about getAttribute and setAttribute you can check here:
https://developer.mozilla.org/en/DOM/element.getAttribute
https://developer.mozilla.org/en/DOM/element.setAttribute
To find out more about DHTML properties you can check the MSDN Resource here:
http://msdn.microsoft.com/en-us/library/ms533055%28VS.85%29.aspx
Example Code using getAttribute and setAttribute:
var link = document.getElementById('link');
var src = link.getAttribute('src');
link.setAttribute('src',src.replace('size=20','size=40'));
I believe getAttribute is more cross-browser friendly.
var link = document.getElementById('link');
var result = link.getAttribute("src").replace('size=20', 'size=45');
Also, the replace function returns a string. It doesn't operate on the string it is called against. This means you have to assign the result.
link.setAttribute("src", result);

Categories

Resources