Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all elements whose id begins with a common string

I have a XSL that created multiple elements with the id of "createdOn" plus a $unique-id

Example : createdOnid0xfff5db30 

I want to find and store these in a variable using JavaScript. I've tried

var dates = document.getElementsById(/createdOn/); 

but that doesn't appear to work.

like image 324
meriley Avatar asked Apr 11 '12 18:04

meriley


People also ask

How do I get all elements of a specific ID?

Use the document. querySelectorAll() method to get all elements whose id starts with a specific string, e.g. document. querySelectorAll('[id^="box"]') . The method returns a NodeList containing all the elements that match the provided selector.

How do I use querySelectorAll document?

Example: If you add a <li> element to a list in the DOM, the list in NodeList will not change. The getElementsByClassName() and getElementsByTagName() methods return a live HTMLCollection. The querySelectorAll() method returns a static NodeList. The childNodes property returns a live NodeList.

What is the syntax of get element by ID?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.


1 Answers

Using jQuery you can use the attr starts with selector:

var dates = $('[id^="createdOnid"]'); 

Using modern browsers, you can use the CSS3 attribute value begins with selector along with querySelectorAll:

var dates = document.querySelectorAll('*[id^="createdOnID"]'); 

But for a fallback for old browsers (and without jQuery) you'll need:

var dateRE = /^createdOnid/; var dates=[],els=document.getElementsByTagName('*'); for (var i=els.length;i--;) if (dateRE.test(els[i].id)) dates.push(els[i]); 
like image 90
Phrogz Avatar answered Sep 26 '22 03:09

Phrogz