最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

parsing html attributes of tag javascript - Stack Overflow

programmeradmin5浏览0评论

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, i.e., "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

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, i.e., "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

Share Improve this question asked Jun 29, 2015 at 7:02 akashrajknakashrajkn 2,3152 gold badges24 silver badges47 bronze badges 1
  • 2 You can either use getAttribute method, or refer to the property directly with its name. Notice, that (exceptionally) a.toString() also returns the value of href attribute. – Teemu Commented Jun 29, 2015 at 7:07
Add a ment  | 

3 Answers 3

Reset to default 4

You need to use the method Element.getAttribute(). See https://developer.mozilla/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];
发布评论

评论列表(0)

  1. 暂无评论