Search code examples
jquerycdata

In this case, Do I need to using CDATA section?


I was found at this code by accident.

//<![CDATA[
jQuery(function() {
  jQuery('#gnb li a').each(function() {
    if (jQuery(this).attr('href')  ===  window.location.pathname) {
      jQuery(this).addClass('on');
    }
    if ("/seoul/timeline/"  ===  window.location.pathname) {
        jQuery('#home_item').addClass('on');
    }

  });
});
//]]>

At that time, I'm didn't known for the CDATA section.

As I searching it is it intended to pass a literally tag(ex.<script>.....</script>), so it prevents an error in the browser.

At the above code, I wasn't found an any tag.

Why do using a CDATA section?


Solution

  • The intention is so you do not need to escape < within your javascript in an XHTML document (which is a form of XML). When enclosed in a CDATA section, < is treated as literal <.

    HTML itself does not recognise CDATA sections, which is why the CDATA start and end tokens are in JS comments.

    For more detail, a similar question was answered at: What is CDATA in HTML?

    As it happens, the example you posted would work fine with or without the two lines that start and end the CDATA section.