0

I'm converting a jQuery script into Javascript but when I try to append via jQuery.append(data) it creates a proper script in head tag of page

jQuery

if (data) {
  $('head').append(data);
}

screenshot attached

while when I do it via Javascript it only appends the data as a string and not as a script tag

Javascript

  if (data) {
    appendTo("head", document.createTextNode(data));
  }

screenshot attached

If I try to append without document.createTextNode by simply doing

if (data) {
    document
      .getElementsByTagName("head")[0]
      .appendChild(data);
  }

then it throws following error

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

while data in has the following (JSON+LD) content

const data = "\n<script type=\"application/ld+json\">\n{\n  \"@context\": \"http://schema.org\",\n  \"@type\": \"BlogPosting\",\n  \"mainEntityOfPage\": {\n    \"@type\": \"WebPage\",\n    \"@id\": \"http://localhost:8080/?p=abbc\"\n  },\n  \"url\": \"http://localhost:8080/?p=abbc\",\n  \"headline\": \"How To workout.\",\n  \"datePublished\": \"2021-12-17T15:15:00-06:00\",\n  \"dateModified\": \"2022-05-31T11:01:15-05:00\",\n    \"author\": {\n    \"@type\": \"Person\",\n    \"name\": \"Laura\",\n    \"url\": \"http://localhost:8080/?a=laura\"\n  },\n      \"wordCount\": \"377\",\n  \"description\": \"Main description  . \"\n}\n</script>"
Barmar
  • 741,623
  • 53
  • 500
  • 612
Mani
  • 2,391
  • 5
  • 37
  • 81
  • The argument to `appendChild()` has to be a DOM element, not a string of HTML. It doesn't parse the HTML. You have to do `document.createElement('script')`. – Barmar Jun 01 '22 at 16:07
  • @Barmar i totally understand stackoverflow policy but regarded question doesn't answer my question – Mani Jun 01 '22 at 16:10
  • 1
    I didn't choose that duplicate, @Ram did. I've replaced it with a different one that may be more helpful. – Barmar Jun 01 '22 at 16:13

0 Answers0