SnakeDoc
SnakeDoc

Reputation: 14361

Get id's containing a string

I'm attempting to get all id's that contain a given string. The full id is not known, only a partial id. Id's appear like so:

<td class="item" id=shipping-1 align="left">$1.00</td>
<td class="item" id=shipping-2 align="left">$6.49</td>
<td class="item" id=shipping-3 align="left">$8.50</td>
// etc...

As you can see, "shipping-" is a constant, but the appended number is dynamic on page load (depends on what shipping options are valid for the receiving address).

I'm not great with javascript, but obviously using getElementById() won't work here.

I would like to avoid doing something clunky like getting id's in a loop until I get an 'undefined'.

I need something like: getElementsContainingString('shipping-')

I need to get an array of these id's, then will read the innerHTML and determine which is cheapest. This must be done dynamically via javascript because we cannot control the page on the server side to perform this logic.

Upvotes: 2

Views: 1316

Answers (5)

Tiberiu C.
Tiberiu C.

Reputation: 3513

You can always use a css selector [attrName^="startsWith"]

var cells = document.querySelectorAll('td[id^="shipping-"]');

Seems to be available from IE7+ and the rest of the browsers.

Sample here : http://jsbin.com/kayov/1/edit

Upvotes: 0

bjb568
bjb568

Reputation: 11498

document.querySelectorAll('[id^="shipping-"]');

No jQuery required. This does a CSS selector for id="shipping-[wildcard]". MDN: Query selector, MDN: Attribute selector. This works with IE 8+, and there are polyfills if you want to support lower.

Upvotes: 3

Drewness
Drewness

Reputation: 5072

This is pretty simple:

var tds = document.getElementsByTagName("td");
for (var i=0; i<tds.length; i++) {
  if (tds[i].id.indexOf("shipping") == 0)
    // Do stuff...
}

Upvotes: 0

Cameron Little
Cameron Little

Reputation: 3711

Try taking a look at this answer: Javascript getElementById base on partial string

You'll then want to use their second fiddle's example: http://jsfiddle.net/xwqKh/1/

They used the following code (not my own):

document.findElementsWithIdLike = function(prefix) {
    var results = [];
    findChildrenWithIdLike(document.body, prefix, results);

    return results;
};

window.findChildrenWithIdLike = function(node, prefix, results) {
    if (node && node.id && node.id.indexOf(prefix) == 0) {
        //match found
        results.push(node);
    }

    //check child nodes
    for (var i = 0; i < node.childNodes.length; i++) {
        var child = node.childNodes[i];
        var childResult = findChildrenWithIdLike(child, prefix, results);
        if (childResult) {
            results.push(childResult);
        }
    }
};

Upvotes: 0

alexbchr
alexbchr

Reputation: 613

If you use JQuery, you can use the following code :

var cells = $("td[id^=item]");

The brackets [] tells to take all td with the attribute id starting with string "item".

Upvotes: 0

Related Questions