Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ID Ends With in pure Javascript

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.

like image 612
Brian Genisio Avatar asked Mar 09 '11 16:03

Brian Genisio


People also ask

What selector would I use to query for all elements with an ID that ends with a particular string?

To get the elements with an ID that ends with a given string, use attribute selector with $ character.

What is $() in JavaScript?

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

How do I add ids to querySelector?

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.

What character is used to target elements with IDS?

The CSS id Selector To select an element with a specific id, write a hash (#) character, followed by the id of the element.


2 Answers

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]"));
like image 192
pimvdb Avatar answered Oct 21 '22 05:10

pimvdb


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

like image 25
ThiefMaster Avatar answered Oct 21 '22 05:10

ThiefMaster