131

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?

Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102
calebo
  • 3,312
  • 10
  • 44
  • 66
  • please show a sample markup for clarity – naveen Aug 09 '11 at 04:57
  • Do you want the id of the element, or the element with the id? – aroth Aug 09 '11 at 04:58
  • I want to get the ID of the element. – calebo Aug 09 '11 at 05:03
  • If this is your own website code, I would recommend that you give each of these elements a class. It will still require some degree of code, but there are many pre-built functions for getElementsByClassName. Some modern browsers natively support said function. – Kranu Aug 09 '11 at 05:53
  • @Kranu - `getElementsByClassName` isn't quite pre-built. If you want it to work correctly in IE (at least, older versions of IE...maybe it's been fixed in newer versions) then you have to patch it up yourself. – aroth Aug 09 '11 at 06:46
  • @Aroth: By prebuilt, I meant that you can find a snippet of code that you can just copy and paste in to add support. The term you're referring to is native support. – Kranu Aug 09 '11 at 07:15
  • Possible duplicate of [jQuery Selector: Id Ends With?](https://stackoverflow.com/questions/609382/jquery-selector-id-ends-with) – Claire May 19 '18 at 09:07

9 Answers9

218

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>
A1rPun
  • 16,287
  • 7
  • 57
  • 90
  • Works for it only gets the first match. – Sophia Feng Mar 19 '15 at 23:21
  • 36
    `querySelectorAll ` is great. Except `document.querySelectorAll('[id^="poll-"]')` returns a list. We need to iterate the list to get the ids instead of using `document.querySelectorAll('[id^="poll-"]').id`. – Sophia Feng Mar 24 '15 at 21:15
  • 3
    What if it were slightly different in that you knew what the END of the dynamic value? In my scenario, it's id="dynamic_constant"? – JoeL Nov 13 '15 at 15:10
  • 4
    @JoeL `^` matches the start, `$` matches the end and `*` matches any position. In your case it would be `id$="dynamic_constant"`. – A1rPun Nov 13 '15 at 15:52
  • 2
    How about the case where I know the start and the end but the middle is dynamic, e.g. `id='user-123456-image'` – Dave Potts Jul 27 '16 at 13:28
  • 4
    Sorry I should have been clearer in my example. How would I pick all the elements with an id that starts with 'user-' AND ends with '-image', but the number in the middle can vary. – Dave Potts Jul 28 '16 at 07:22
  • 7
    @DavePotts Use `[id^=user-][id$=-image]` :) – A1rPun Aug 03 '16 at 13:53
  • Above regex syntax puzzles me: Why is it '[id^="poll-"]' ? Why not '[id="^poll-"]' or '[id=^"poll-"]' ? – user1785730 May 15 '17 at 07:59
  • 2
    @user1785730 Because it only looks like a regular expression, it isn't one. It's just a feature of the queryselector syntax. – A1rPun May 15 '17 at 10:13
  • 2
    Actually, it's CSS Selector syntax (https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) that is used by the querySelector API – Ilya Streltsyn Dec 19 '19 at 07:48
  • how to use this if start and end are empty suppose document.querySelector('[id="-poll-"]').id; – sanjeet pal Feb 16 '20 at 19:12
11

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/

naveen
  • 53,448
  • 46
  • 161
  • 251
10

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.

Serge Stroobandt
  • 28,495
  • 9
  • 107
  • 102
4

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/

aroth
  • 54,026
  • 20
  • 135
  • 176
2

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);
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Problem is I only know the base, but I don't know the num value. – calebo Aug 09 '11 at 05:07
  • Then, you can't use getElementById without the whole ID name. If you post your actual HTML, we could help with a different strategy. With your new example, you could use a CSS3 strategy for an ID that starts with "post-", but there are only a few browsers that you can do that with plain JS/browser (CSS3 selector engine support). It would be much better to use a selector engine in jQuery, Sizzle, YUI3, etc... – jfriend00 Aug 09 '11 at 05:11
  • I just need to be able to set a variable with the element with the id starting with 'poll-' as it's value.
    – calebo Aug 09 '11 at 05:16
  • The structure of the tags, IDs and classes are all you have if you're not going to use a more advanced selector engine. If you don't want to share and won't use a selector engine, then we're at a dead-end. If you would just tell us what kind of tag it is, we could look at all of them for a partial ID match. – jfriend00 Aug 09 '11 at 05:18
  • OK, now that you've shown some HTML, I added two different functions that would find those type of form elements. – jfriend00 Aug 09 '11 at 05:27
1

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.

Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • Keep in mind that getElementsByClassName is not supported in some older browsers (any version of IE before IE9). – jfriend00 Aug 09 '11 at 04:57
  • @jfriend00 Good call. That's one reason I use jQuery for all of my DOM script, so I don't have to remember that kind of thing. – Joe Enos Aug 09 '11 at 04:59
  • When I don't have jQuery and don't want to pull it into the page, I use the Sizzle library which (I think) is the selector engine inside of jQuery. It solves this problem too and gives you full selector logic. Not much reason these days to live with only what IE8 can do natively. – jfriend00 Aug 09 '11 at 05:01
0
<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-"]'

jester
  • 238
  • 5
  • 13
0

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));
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

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)
Shaiful Islam
  • 335
  • 2
  • 12