3

I would like to know if it is possible to capture a commented remark using JavaScript.

The remark will look like this on the soruce code:

<div id='ContainerId'>
<!-- NON IDEAL REASON: 90 min time window depart arrive -->
<b>1,107.45 GBP</b><br />
<!--LLF: 1107.45 -->
</div>

I need to save that value (in this case 1107.45) inside a variable.

This doesn't seem to work:

var LLF = jQuery("contains('LLF')");

Any ideas?

Thanks!

fedxc
  • 195
  • 1
  • 1
  • 11
  • Are you generating the comment in your server side code? – bygrace May 25 '12 at 14:47
  • possible duplicate of [Selecting HTML Comments with jQuery](http://stackoverflow.com/questions/1623734/selecting-html-comments-with-jquery) –  May 25 '12 at 15:12
  • Check out the following post, it may give you a head-start: [Selecting HTML Comments with jQuery](http://stackoverflow.com/questions/1623734/selecting-html-comments-with-jquery) – Shant May 25 '12 at 14:46
  • There's an article about it here: [jQuery Comments() Plug-in To Access HTML Comments For DOM Templating](http://www.bennadel.com/blog/1563-jQuery-Comments-Plug-in-To-Access-HTML-Comments-For-DOM-Templating.htm) – WojtekT May 25 '12 at 14:46
  • @bygrace Yes, this is generated on the server side. – fedxc May 25 '12 at 15:44
  • Ok, it would probably be better if you just store it in a javascript variable then. I don't know what server-side language you are using but you could do something like `var LLF = '<%= LLF %>';` (for .NET) or `var LLF = '= LLF %>';` (for php) – bygrace May 25 '12 at 15:49
  • If you are going for storing data in context of something on your page then you should look into useing the `data-*` attribute (http://html5doctor.com/html5-custom-data-attributes/) – bygrace May 25 '12 at 15:56
  • Is the same content you're targeting actually going to be in the `` element as well? –  May 25 '12 at 16:21

1 Answers1

5
$('#ContainerId').contents().filter(function(){
    return this.nodeType === 8 // Comment node
});

Live DEMO

And the full code:

var comment = $('#ContainerId').contents().filter(function() {
    return this.nodeType === 8 // Comment node
})[0].nodeValue;

console.log(comment.match(/\d+\.\d+/g));​​​​​

Live DEMO

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • This is what I am looking for, thank you. Nevertheless, I realized that I have other commented lines under the same DIV, so it's capturing the first line instead of the desired one. How could I filter the node value? Edit: I have updated the source code to reflect the code in place. – fedxc May 25 '12 at 15:32
  • Sorry for my lame comment, just realized this: [0].nodeValue; – fedxc May 25 '12 at 16:15