-1

I'm converting a jQuery script into Javascript but appendChild is throwing error where jQuery was not. Below is the original code snippets

jQuery

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

Javascript

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

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>"
Mani
  • 2,304
  • 3
  • 34
  • 71
  • Note `$("made_up_tag").append(data)` will also "not throw an error" - it won't actually do anything, but won't throw an error. – freedomn-m Jun 01 '22 at 14:13
  • The error message tells you the problem: `parameter 1 is not of type 'Node'` - you must pass a Node to appendChild, not a plain HTML string. Working example: https://stackoverflow.com/a/8407544/2181514 – freedomn-m Jun 01 '22 at 14:24
  • Existing question has specifically this answer: https://stackoverflow.com/a/34279370/2181514 - as a one liner: `document.getElementsByTagName('head')[0].appendChild(document.createTextNode(data));` – freedomn-m Jun 01 '22 at 14:27

1 Answers1

0
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>'

Try this

Uttam Nath
  • 73
  • 7