Selecting an item by content using jQuery

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

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

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

I need to be able to identify this element and fire the event with one click. Once the click occurs, I should be able to easily parse the identifier (elementid1) from the content.

However, these elements are not always just div. Sometimes they are from H1 to H6, etc. How will I look for these events

OR

Alternatively, I could scroll through all the elements (the part I don’t know how to do this), set a custom attribute with an identifier, and then create jQuery events for elements with an attribute equal to something. If someone has an idea of ​​how to go through each element of the DOM (preferably only children, since parents will also have children content ...), then this will also work.

Note:

Normally I would use the contains () selector, but since this identifier is a comment, not text, it does not seem to work.

+3
source share
2 answers

Try it...

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

jsFiddle .

+8
source

, nodeType = COMMENT_NODE (8) ... ...

jsFiddle

+2

Source: https://habr.com/ru/post/1793788/


All Articles