Andrew M
Andrew M

Reputation: 4288

Select element by content using jQuery

I am currently building an application that requires the identification of an element by its content. Normally I would use the ID of an element to identify it, but in this case it is not possible since the content is user generated.

I have a PHP script that outputs some content, part of which is user entered. For example:

<!-- elementid1 -->
This is user generated text. Lorem ipsum...

I need to be able to identify this element and fire an event on a click. Once the click happens, I should be able to parse the ID (elementid1) from the content easily.

However, these elements aren't always just DIVs. Sometimes they are H1 through H6, etc. How would I go about detecting these events

OR

Alternatively, I could loop through all elements (the part I don't know how to do), setting a custom attribute with the ID, then creating jQuery events for elements with the attribute equalling something. If anyone has insight on how to loop through every DOM element (preferably only the children, since the parents would have the content of the children as well...) then this would also work.

A Note:

Normally I would use the contains() selector, but since this ID is a comment and not text it doesn't seem to work.

Upvotes: 3

Views: 1117

Answers (2)

aavezel
aavezel

Reputation: 604

You can create custom selector which will search the children with nodeType = COMMENT_NODE (8) and specific content ... But this is a long time...

jsFiddle

Upvotes: 2

alex
alex

Reputation: 490183

Try this...

$('*').filter(function() {
   return $(this).html().match('<!-- elementid1 -->');
});

jsFiddle.

Upvotes: 8

Related Questions