基于部分字符串的 Javascript getElementById

发布于 2024-11-28 17:26:33 字数 253 浏览 5 评论 0原文

我需要获取一个元素的 ID,但该值是动态的,只有它的开头始终是相同的。

这是代码片段。

<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite">

ID 始终以 poll- 开头,然后数字是动态的。

如何仅使用 JavaScript 而不是 jQuery 获取 ID?

I need to get the ID of an element but the value is dynamic with only the beginning of it is the same always.

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.

How can I get the ID using just JavaScript and not jQuery?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

皇甫轩 2024-12-05 17:26:33

可以使用querySelector 为此:

document.querySelector('[id^="poll-"]').id;

选择器意味着:
获取属性 [id] 以 (^=) 字符串 "poll-" 开头的元素。

^ 匹配开头
* 匹配任何位置
$ 匹配结尾的

示例

console.log(document.querySelector('[id^=poll-]').id)
<form id="poll-1225962377536"></form>

You can use the querySelector for that:

document.querySelector('[id^="poll-"]').id;

The selector means:
get an element where the attribute [id] begins with (^=) the string "poll-".

^ matches the start
* matches any position
$ matches the end

Example

console.log(document.querySelector('[id^=poll-]').id)
<form id="poll-1225962377536"></form>

萌︼了一个春 2024-12-05 17:26:33

使用现代枚举的 querySelectorAll

polls = document.querySelectorAll('[id ^= "poll-"]');
Array.prototype.forEach.call(polls, callback);

function callback(element, iterator) {
    console.log(iterator, element.id);
}

第一行选择 id 以字符串 poll- 开头 ^= 的所有元素。
第二行调用枚举和回调函数。

querySelectorAll with modern enumeration

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 in which id starts ^= with the string poll-.
The second line evokes the enumeration and a callback function.

泪是无色的血 2024-12-05 17:26:33

试试这个。

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;
}

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>

在这里将其称为

var postedOnes = getElementsByIdStartsWith("posts", "div", "post-");

演示:http://jsfiddle.net/naveen/P4cFu/

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.

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

苏璃陌 2024-12-05 17:26:33

鉴于您想要的是仅根据前缀确定元素的完整 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;
        }
    }
};

这是一个示例: http://jsfiddle.net/xwqKh/

是请注意,动态元素 ID(例如您正在使用的元素 ID)通常用于保证单个页面上元素 ID 的唯一性。这意味着很可能有多个元素共享相同的前缀。也许您想找到全部。

如果您想查找具有给定前缀的所有元素,而不仅仅是第一个元素,您可以使用类似于此处演示的内容: http://jsfiddle.net/xwqKh/1/

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:

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/

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.

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/

岁月如刀 2024-12-05 17:26:33

我不完全确定我知道你在问什么,但你可以使用字符串函数来创建你正在寻找的实际 ID。

var base = "common";
var num = 3;

var o = document.getElementById(base + num);  // will find id="common3"

如果您不知道实际的 ID,则无法使用 getElementById 查找对象,您必须以其他方式查找它(按类名、按标签类型、按属性、按父级、按子级, ETC...)。

现在您终于给了我们一些 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);
}

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.

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...).

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

// 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);
}
独木成林 2024-12-05 17:26:33

您可能必须给它一个常量类并调用 getElementsByClassName,或者只使用 getElementsByTagName,然后循环遍历结果,检查名称。

我建议您看看您的根本问题,并找出一种可以提前知道 ID 的方法。

也许如果您发布更多有关为什么会收到此信息的信息,我们可以找到更好的替代方案。

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.

I'd suggest looking at your underlying problem and figure out a way where you can know the ID in advance.

Maybe if you posted a little more about why you're getting this, we could find a better alternative.

触ぅ动初心 2024-12-05 17:26:33

您可以使用 id 属性获取 id,然后使用 substr 方法删除它的第一部分,然后可选地使用 parseInt 将其转换转换为数字:

var id = theElement.id.substr(5);

或:

var id = parseInt(theElement.id.substr(5));

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:

var id = theElement.id.substr(5);

or:

var id = parseInt(theElement.id.substr(5));
燃情 2024-12-05 17:26:33
<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite" target="_blank">

ID 始终以“post-”开头,然后数字是动态的。

请检查您的 ID 名称,“投票”和“发布”有很大不同。

正如已经回答的,您可以使用querySelector:

var selectors = '[id^="poll-"]';
element = document.querySelector(selectors).id;

但是如果您继续查询“post”,querySelector将找不到“poll”: '[id^="post-"]'

<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite" target="_blank">

The ID always starts with 'post-' then the numbers are dynamic.

Please check your id names, "poll" and "post" are very different.

As already answered, you can use querySelector:

var selectors = '[id^="poll-"]';
element = document.querySelector(selectors).id;

but querySelector will not find "poll" if you keep querying for "post": '[id^="post-"]'

骑趴 2024-12-05 17:26:33

如果您需要最后一个 id,您可以这样做:

var id_list = document.querySelectorAll('[id^="image-"]')
var last_id = id_list.length
alert(last_id)

If you need last id, you can do that:

var id_list = document.querySelectorAll('[id^="image-"]')
var last_id = id_list.length
alert(last_id)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文