1

i'm trying to find and alter the last comment node in a page (which will change periodically).

something like

<!-- first comment -->
<!-- second comment -->
<!-- third comment -->
<something></something>

the element following the last comment will always be "something", maybe there's a way to just grab the node before "something"? having a hard time unpacking how dealing with nodes works

edit: i've found answers about finding all the comment nodes but can't figure out how to select only the last one. an additional hazard is that this is a weird project where i need to specifically use custom elements without ids or classes

milpool
  • 1,141
  • 10
  • 18
  • Possible duplicate of [Selecting HTML comments with jQuery](https://stackoverflow.com/questions/1623734/selecting-html-comments-with-jquery) – Tyler Roper Nov 13 '18 at 21:55
  • Can you improve your html markup with the comments structure? – Shidersz Nov 13 '18 at 22:00
  • @TylerRoper this is for a weird project with special crazy rules so i'm trying to avoid plugins though that looks like a good way. i'm currently using the "return this.nodeType == 8;" technique in other parts of my code but can't figure out how to use that to select only the last comment – milpool Nov 13 '18 at 22:46

1 Answers1

1

This is interesting, and I'm not sure if this is the best method, but if you can count on it always being before a certain DOM element, then you could start at that element and work backwards until you find the first comment. See this code as an example.

let something = document.getElementsByTagName("something")[0]
let currentNode = something

// 8 is the node type for a comment
while (currentNode !== null && currentNode.nodeType !== 8) {
  currentNode = currentNode.previousSibling
}

console.log(currentNode.data)
<!-- first comment -->
<!-- second comment -->
<!-- third comment -->
<something></something>
Jordan Soltman
  • 3,795
  • 17
  • 31
  • ooh this is very close!! but i'm doing a weird project where i can't use ids just dom elements like and i can't figure out how to alter this code to work that way. ideas? – milpool Nov 13 '18 at 22:43
  • 1
    Well, if you have to use "something" you can select by tag name, and then get the first element. I updated my answer. – Jordan Soltman Nov 13 '18 at 23:03
  • YES this is perfect thank you!! i'm new to pure js and didn't know about selecting by tag names, that's great! – milpool Nov 13 '18 at 23:12