Javascript 基于部分字符串的Javascript getElementById
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6991494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript getElementById based on a partial string
提问by calebo
I need to get the ID of an element but the value is dynamic with only the beginning of it is the same always.
我需要获取元素的 ID,但该值是动态的,只有它的开头始终相同。
Heres a snippet of the code.
这是代码的片段。
<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite">
The ID always starts with poll-
then the numbers are dynamic.
ID始终以poll-
数字开头,然后数字是动态的。
How can I get the ID using just JavaScript and not jQuery?
如何仅使用 JavaScript 而不是 jQuery 获取 ID?
回答by A1rPun
You can usethe querySelectorfor that:
document.querySelector('[id^="poll-"]').id;
The selector means: get an element where the attribute [id]
begins with the string "poll-"
.
选择器的意思是:获取属性[id]
以字符串开头的元素"poll-"
。
^
matches the start*
matches any position$
matches the end
^
匹配开始*
匹配任何位置$
匹配结束
jsfiddle
提琴手
回答by naveen
Try this.
尝试这个。
function getElementsByIdStartsWith(container, selectorTag, prefix) {
var items = [];
var myPosts = document.getElementById(container).getElementsByTagName(selectorTag);
for (var i = 0; i < myPosts.length; i++) {
//omitting undefined null check for brevity
if (myPosts[i].id.lastIndexOf(prefix, 0) === 0) {
items.push(myPosts[i]);
}
}
return items;
}
Sample HTML Markup.
示例 HTML 标记。
<div id="posts">
<div id="post-1">post 1</div>
<div id="post-12">post 12</div>
<div id="post-123">post 123</div>
<div id="pst-123">post 123</div>
</div>
Call it like
叫它像
var postedOnes = getElementsByIdStartsWith("posts", "div", "post-");
Demo here: http://jsfiddle.net/naveen/P4cFu/
演示在这里:http: //jsfiddle.net/naveen/P4cFu/
回答by aroth
Given that what you want is to determine the full id of the element based upon just the prefix, you're going to have to do a search of the entire DOM (or at least, a search of an entire subtree if you know of some element that is always guaranteed to contain your target element). You can do this with something like:
鉴于您想要的是仅根据前缀确定元素的完整 id,您将不得不搜索整个 DOM(或者至少,如果您知道一些,则搜索整个子树始终保证包含目标元素的元素)。您可以使用以下方法执行此操作:
function findChildWithIdLike(node, prefix) {
if (node && node.id && node.id.indexOf(prefix) == 0) {
//match found
return node;
}
//no match, check child nodes
for (var index = 0; index < node.childNodes.length; index++) {
var child = node.childNodes[index];
var childResult = findChildWithIdLike(child, prefix);
if (childResult) {
return childResult;
}
}
};
Here is an example: http://jsfiddle.net/xwqKh/
这是一个例子:http: //jsfiddle.net/xwqKh/
Be aware that dynamic element ids like the ones you are working with are typically used to guarantee uniqueness of element ids on a single page. Meaning that it is likely that there are multiple elements that share the same prefix. Probably you want to find them all.
请注意,像您正在使用的动态元素 ID 通常用于保证单个页面上元素 ID 的唯一性。这意味着可能有多个元素共享相同的前缀。可能您想全部找到它们。
If you want to find all of the elements that have a given prefix, instead of just the first one, you can use something like what is demonstrated here: http://jsfiddle.net/xwqKh/1/
如果您想找到所有具有给定前缀的元素,而不仅仅是第一个,您可以使用类似于此处演示的内容:http: //jsfiddle.net/xwqKh/1/
回答by Serge Stroobandt
querySelectorAll
with modern enumeration
querySelectorAll
与现代枚举
polls = document.querySelectorAll('[id ^= "poll-"]');
Array.prototype.forEach.call(polls, callback);
function callback(element, iterator) {
console.log(iterator, element.id);
}
The first line selects all elements which id
starts with the string poll-
.
The second line evokes the enumeration and a callback function.
第一行选择所有id
以 string 开头的元素poll-
。第二行唤起了枚举和回调函数。
回答by jfriend00
I'm not entirely sure I know what you're asking about, but you can use string functions to create the actual ID that you're looking for.
我不完全确定我知道你在问什么,但你可以使用字符串函数来创建你正在寻找的实际 ID。
var base = "common";
var num = 3;
var o = document.getElementById(base + num); // will find id="common3"
If you don't know the actual ID, then you can't look up the object with getElementById, you'd have to find it some other way (by class name, by tag type, by attribute, by parent, by child, etc...).
如果您不知道实际 ID,则无法使用 getElementById 查找对象,您必须通过其他方式(按类名、按标签类型、按属性、按父项、按子项、等等...)。
Now that you've finally given us some of the HTML, you could use this plain JS to find all form elements that have an ID that starts with "poll-":
现在你终于给了我们一些 HTML,你可以使用这个普通的 JS 来查找 ID 以“poll-”开头的所有表单元素:
// get a list of all form objects that have the right type of ID
function findPollForms() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
results.push(list[i]);
}
}
return(results);
}
// return the ID of the first form object that has the right type of ID
function findFirstPollFormID() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
return(id);
}
}
return(null);
}
回答by Joe Enos
You'll probably have to either give it a constant class and call getElementsByClassName
, or maybe just use getElementsByTagName
, and loop through your results, checking the name.
您可能必须给它一个常量类并调用getElementsByClassName
,或者可能只是使用getElementsByTagName
,然后循环查看您的结果,检查名称。
I'd suggest looking at your underlying problem and figure out a way where you can know the ID in advance.
我建议查看您的潜在问题并找出一种可以提前知道 ID 的方法。
Maybe if you posted a little more about why you're getting this, we could find a better alternative.
也许如果您发布更多关于为什么会得到这个的信息,我们可以找到更好的选择。
回答by Guffa
You use the id
property to the get the id, then the substr
method to remove the first part of it, then optionally parseInt
to turn it into a number:
您使用该id
属性获取 id,然后使用substr
删除它的第一部分的方法,然后可选择parseInt
将其转换为数字:
var id = theElement.id.substr(5);
or:
或者:
var id = parseInt(theElement.id.substr(5));
回答by jester
<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite" target="_blank">
The ID always starts with 'post-' then the numbers are dynamic.
ID 总是以“post-”开头,然后数字是动态的。
Please check your id names, "poll" and "post" are very different.
请检查您的 id 名称,“poll”和“post”非常不同。
As already answered, you can use querySelector:
正如已经回答的那样,您可以使用 querySelector:
var selectors = '[id^="poll-"]';
element = document.querySelector(selectors).id;
but querySelector will not find "poll" if you keep querying for "post": '[id^="post-"]'
但是如果您继续查询“post”,querySelector 将找不到“poll”: '[id^="post-"]'