通过Id获取多个元素 [英] Get multiple elements by Id

查看:153
本文介绍了通过Id获取多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < a id =testname = 名称1>< / a> 
< a id =testname =Name 2>< / a>
< a id =testname =Name 3>< / a>

ID始终相同,但名称会更改。



我需要填充这些锚标签的名称列表,例如;名字1,名字2,名字3.这是我到目前为止的地方:

  document.write(document。的getElementById( 自述)的名称)。 

这会写出第一个锚标记的名称。我需要通过Id获取多个元素的方法。






非常感谢任何帮助。

解决方案

如果您可以更改标记,则可能需要使用 class

 <! -  html  - > 
< a class =testname =Name 1>< / a>
< a class =testname =Name 2>< / a>
< a class =testname =Name 3>< / a>

// javascript
var elements = document.getElementsByClassName(test);
var names ='';
for(var i = 0; i< elements.length; i ++){
names + = elements [i] .name;
}
document.write(names);

jsfiddle演示


I have a page with anchor tags throughout the body like this:

<a id="test" name="Name 1"></a>
<a id="test" name="Name 2"></a>
<a id="test" name="Name 3"></a>

The ID is always the same but the name changes.

I need to populate a list of the names of these anchor tags, for example; Name 1, Name 2, Name 3. This is where I've got to so far:

document.write(document.getElementById("readme").name);

This writes out the name of the first anchor tag. I'm in need of a way to get multiple elements by Id.


Any help is greatly appreciated.

解决方案

If you can change the markup, you might want to use class instead.

<!-- html -->
<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>

// javascript
var elements = document.getElementsByClassName("test");
var names = '';
for(var i=0; i<elements.length; i++) {
    names += elements[i].name;
}
document.write(names);

jsfiddle demo

这篇关于通过Id获取多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆