How to select HTML with jQuery when it does not have unique identifying attributes but has HTML comment?

I am writing a custom script for a forum that I frequent. It is designed to remove signatures from the board when viewing, because they are distracting and annoying, and they have no way to disable them in the settings.

In any case, I can run my own scripts using the useful Chrome extension. I can modify any parts of the page where the HTML nodes have classes, identifiers, or even attributes with slightly unique information, but I cannot figure out how to select and remove the following HTML using jQuery.

<tr> <td colspan="2"> <!--Signature--> <div class="resultText"> <!-- sig --> <div>Signature text</div> <!-- / sig --> </div> </td> </tr> 

If there was a way, I could capture the parent <!--Signature--> , which would be perfect, but I'm not sure if this is possible.

Here is a screenshot of a larger HTML tree for the entire forum post:

http://www.codetunnel.com/content/images/htmltree.jpg

There is one resultText class, but this class is used wherever there is text entered by the user, and not just the signature. Therefore, I cannot understand this. Any help is appreciated :)

+4
source share
3 answers

You can use .contents() to get all the child nodes of an element: http://api.jquery.com/contents

From the docs:

Get the children of each element in the set of matched elements, including text and node comments.

 $('tr').each(function (index, obj) { $(this).children('td').contents();//this selects all the nodes in each TD element in the table, including comment nodes }); 

Here is a demo: http://jsfiddle.net/NLhz9/1/

+1
source

Even if the resultText class resultText used elsewhere, I still recommend using the class selector as a starting point, otherwise you will search for comment nodes throughout the document.

From the matched elements, you can get the content () of your parents, use the filter () to isolate the comment nodes (their nodeType property is 8 ) and compare the value of these nodes with the Signature line:

 $(".resultText").parent().each(function() { var $this = $(this); var signature = $this.contents().filter(function() { return this.nodeType == 8 && this.nodeValue == "Signature"; }); if (signature.length) { // Signature found, $this is the <td> element. $this.closest("tr").remove(); // For example. } }); 
+5
source

Since the script is mostly for you, use xpath to search for comments.

Try something like this:

 var comment, comments = document.evaluate('//comment()', document); while ((comment=comments.iterateNext())) { if (comment.data=='Signature') { // found one comment.parentNode.parentNode.removeChild(comment.parentNode); } } 
0
source

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


All Articles