I am working in a Javascript library that brings in jQuery for one thing: an "ends with" selector. It looks like this:
$('[id$=foo]')
It will find the elements in which the id
ends with "foo".
I am looking to do this without jQuery (straight JavaScript). How might you go about this? I'd also like it to be as efficient as reasonably possible.
To get the elements with an ID that ends with a given string, use attribute selector with $ character.
$() The $() function is shorthand for the getElementByID method, which, as noted above, returns the ID of a specific element of an HTML DOM. It's frequently used for manipulating elements in a document. $() allows for shorter and more efficient JavaScript coding. Traditional method: document.
To add an id attribute to an element: Select the element using the document. querySelector() method. Use the setAttribute() method to add an id attribute to the element.
The CSS id Selector To select an element with a specific id, write a hash (#) character, followed by the id of the element.
Use querySelectorAll
, not available in all browsers (like IE 5/6/7/8) though. It basically works like jQuery:
http://jsfiddle.net/BBaFa/2/
console.log(document.querySelectorAll("[id$=foo]"));
You will need to iterate over all elements on the page and then use string functions to test it. The only optimizations I can think of is changing the starting point - i.e. not document.body
but some other element where you know your element will be a child of - or you could use document.getElementsByTagName()
to get an element list if you know the tag name of the elements.
However, your task would be much easier if you could use some 3rd-party-javascript, e.g. Sizzle (4k minified, the same selector engine jQuery uses).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With