I ran into the following situation and am not able to figure out the solution, i am new to javascript, and I tried to search the internet, but couldn't find a viable solution. 1) I want to get attributes of the tag queried for. For example if I have a tag as follows
<a href = "pqr/dl/"> docName </a>
how do I get the value of href? By doing
el.getElementsByTagName("a")[0].childNodes[0].nodeValue
I can get only the value of the tag, ie, "docName" by doing this.
2) How do I query for the "img" tag? I have an image tag as follows
<img src = "/icons/alpha.gif" alt="[DIR]">
if I do
console.log(el.getElementsByTagName("img")[0].childNodes[0].nodeValue)
it is printing "null" on the console. I need the values of src and alt.
Thanks in advance
You need to use the method Element.getAttribute(). See https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
var href = el.getElementsByTagName("a")[0].childNodes[0].getAttribute("href");
var src = el.getElementsByTagName("img")[0].childNodes[0].getAttribute("src");
var alt = el.getElementsByTagName("img")[0].childNodes[0].getAttribute("alt");
you can use getAttribute()
method.
var href = document.getElementsByTagName("a")[0].getAttribute("href"); var scr = document.getElementsByTagName("img")[0].getAttribute("src"); var alt = document.getElementsByTagName("img")[0].getAttribute("alt"); alert('href:' +href+' scr:'+scr+' alt:'+alt);
<a href = "pqr/dl/"> docName </a> <img src = "/icons/alpha.gif" alt="[DIR]">
Try:
document.querySelectorAll("a")[0].getAttribute('href');
and for image:
document.querySelectorAll("img")[0];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.