An error has occurred: String cannot have property 'innerText' created

I'm encountering an issue while attempting to dynamically add posts to my post div. The problem arises when I try to include image URLs in the process. Switching from innerText to innerHTML did not resolve the issue, and the array I added is also not being displayed.

// Defining DOM variables 
let button = document.getElementById("btn");
let postForm = document.getElementById("post-form");
let displayPostsCont = document.querySelector(".displayPosts");
let title = document.getElementById("postTitle");
let author = document.getElementById("authorName");
let text = document.getElementById("textP");
let image = document.getElementById("newPostImageUrl");

// Array where newly added posts will be stored
const posts = [{
  title: "My first blog post",
  author: "Kam",
  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis id consectetur purus ut faucibus pulvinar elementum integer enim. Pretium aenean pharetra magna ac placerat vestibulum lectus.",
  image: "https://images.pexels.com/photos/936048/pexels-photo-936048.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
  },
  {
  title: "My second blog post",
  author: "Kam",
  text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis id consectetur purus ut faucibus pulvinar elementum integer enim. Pretium aenean pharetra magna ac placerat vestibulum lectus.",
  image: "https://images.pexels.com/photos/936048/pexels-photo-936048.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
  }
];

const addPost = (title, author, text, image) => {

}


// Creating the blog post with elements and then appending it

const createBlogPostElement = ({title, author, text, image}) => {
  // Create elements
  const postDiv = document.createElement('div');
  const blogPostTitle = document.createElement('h2');
  const authorName = document.createElement('h6');
  const authorPost = document.createElement('p');
  const authorImg = document.createElement('img').src = "";

  // Add content
  blogPostTitle.innerText = "Blog post title: " + title;
  authorName.innerText = "Author name: " + author;
  authorPost.innerText = "post: " + text;
  authorImg.innerText = "image: " + image;

  // Append to the DOM
  postDiv.append(blogPostTitle, authorName, authorPost, authorImg);
  displayPostsCont.appendChild(postDiv);
}

posts.forEach(createBlogPostElement);

Answer №1

This claim raises suspicions on two fronts:

const authorImg = document.createElement('img').src = "";
  1. The variable authorImg will contain the value of the assignment (the empty string), not a reference to the img element.

  2. If it were intended as a reference to the img element, img elements cannot have content other than the image itself and alt text. This means you cannot set their innerText (or innerHTML, or append other elements to them).

You likely meant to do this instead:

const authorImg = document.createElement("img");
authorImg.src = image;

(Then later remove the statement

authorImg.innerText = "image: " + image;
)

You could also consider:

authorImg.setAttribute("alt", "an appropriate description of the image for accessibility");

// defining DOM variables
let button = document.getElementById("btn");
let postForm = document.getElementById("post-form");
let displayPostsCont = document.querySelector(".displayPosts");
let title = document.getElementById("postTitle");
let author = document.getElementById("authorName");
let text = document.getElementById("textP");
let image = document.getElementById("newPostImageUrl");

// when a new post is added, it will be pushed into this array
const posts = [
    {
        title: "My first blog post",
        author: "Kam",
        text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis id consectetur purus ut faucibus pulvinar elementum integer enim. Pretium aenean pharetra magna ac placerat vestibulum lectus.",
        image: "https://images.pexels.com/photos/936048/pexels-photo-936048.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
    },
    {
        title: "My second blog post",
        author: "Kam",
        text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis id consectetur purus ut faucibus pulvinar elementum integer enim. Pretium aenean pharetra magna ac placerat vestibulum lectus.",
        image: "https://images.pexels.com/photos/936048/pexels-photo-936048.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
    },
];

const addPost = (title, author, text, image) => {};

// Create the blog post with elements, then append it

const createBlogPostElement = ({ title, author, text, image }) => {
    //create elements
    const postDiv = document.createElement("div");
    const blogPostTitle = document.createElement("h2");
    const authorName = document.createElement("h6");
    const authorPost = document.createElement("p");
    const authorImg = document.createElement("img");
    authorImg.src = image;

    // add in content
    blogPostTitle.innerText = "Blog post title: " + title;
    authorName.innerText = "Author name: " + author;
    authorPost.innerText = "post: " + text;

    // add  to the DOM
    postDiv.append(blogPostTitle, authorName, authorPost, authorImg);
    displayPostsCont.appendChild(postDiv);
};

posts.forEach(createBlogPostElement);
<div class="displayPosts"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating the value of a Javascript variable from a separate file

Hello there! I have a file named map.php and I need to modify the center value in the code to be based on a different value provided by another JavaScript file called template.js. In the past, I was able to change other HTML values using setAttribute and q ...

Issue with hook not updating when invoked inside useEffect

I'm encountering an issue with updating the state after fetching data from my API. The API response seems to be correct, but for some reason, my weatherData-hook is not getting updated and it returns undefined. Can anyone point out what mistake I migh ...

Parsing XML to JSON using JavaScript

I came across this JavaScript function on Stack Overflow that I've been using to convert XML to JSON: function xmlToJson(xml) { try { var obj = {}; if (xml.nodeType == 1) { if (xml.attributes.length > 0) { ...

Creating shared VB array initializers for the NerdDinner application can be done by following these steps

Currently, I am working my way through the NerdDinner tutorial, where I am converting it to VB as part of my exercise. I have just passed the C# Yield statement but now I am facing a challenge with Shared VB Array Initializers. static IDictionary<strin ...

Guide to sending JSON data through the Wufoo Entries API

It seems the current documentation is lacking in detailing the proper procedure for submitting forms via Ajax. Although there is The Entries POST API, it specifically discusses xml and lacks an example payload. Upon further investigation, I discovered Wuf ...

A Vue computed property is returning the entire function instead of the expected value

One of my computed properties is set up like this: methods: { url_refresh: function (id) { return `${this.url_base}?start=${Date.now()}` } } However, when I attempt to print the value on mount: mounted() { console.log(this.url_refresh) ...

Can you create reusable components in Wordpress that are encapsulated?

In my quest to explore innovative approaches to Wordpress theme development, I have stumbled upon a variety of options such as the "Roots Sage" starter theme, the "Themosis Framework," and "Flynt." While these solutions address intriguing problems, they do ...

Encountering a problem while submitting the form - there appears to be an unexpected "s" token in the

This is my first attempt at creating a contact form using Node.js with Nodemailer. The goal is to have the form submitted through the website and sent directly to your inbox. Here is a snippet of my app.js file in the public folder: const form = document. ...

What is the functionality of the ... operator in PHP?

During my daily office tasks, I often encounter various types of multidimensional arrays that sometimes need to be flattened into a single dimension for efficiency. My preferred method is usually using call_user_func_array with the array_merge parameter. ...

When examining an element in an Angular application using Chrome Dev Tools, why do I not observe raw HTML code?

Just as the title suggests, my question is: Even if browsers don't understand Angular, why am I able to see Angular elements while inspecting the DOM despite using AOT (Ahead-Of-Time Compilation) which means there is no Angular compiler in the browse ...

There seems to be a connection issue between my Jquery and HTML, as they

I've hit a roadblock because my jQuery isn't connecting and I can't seem to figure out why. It's been stumping me for hours. Here is the HTML code snippet from exercise6.html: <!DOCTYPE html> <html lang="en> <h ...

Establish the editor's starting state

Currently, I am utilizing lexical and aiming to establish initial text for the editor. At the moment, my approach involves hardcoding the initial text, but it seems I cannot simply pass a String as anticipated. Instead, the format required is JSON. Hence ...

Identifying the Operating System and Applying the Appropriate Stylesheet

I am trying to detect the Windows operating system and assign a specific stylesheet for Windows only. Below is the code snippet I have been using: $(function() { if (navigator.appVersion.indexOf("Win")!=-1) { $(document ...

Display/Collapse SELECT choices?

Consider this scenario : <select class="form-control" name="blah" ng-model="$ctrl.form.blah" ng-options="item.id as item.name group by item.etype | uppercase for item in $ctrl.opts"></select> My goal is to toggle the display of each GROUP b ...

The AngularJS model does not reflect changes after I make edits in the editor

Currently, I am utilizing Jhtmlarea and have created a custom directive as follows: test.directive('jhtml', function () { return { restrict: 'A', replace: false, link: function (s ...

Activate the parent navigation link when on sub-pages

I want to ensure that the parent navigation item is highlighted when a user is on a child page based on the URL. For example, if the user is currently viewing foo1-child and the parent is foo1, I need to apply the active class to Foo 1: http://foo.com/foo ...

Verify that the user visits the URL in next.js

I need to ensure that a function only runs the first time a user visits a page, but not on subsequent visits. For example: When a user first opens the HOME page, a specific condition must be met. When they then visit the /about page, the condition for th ...

Experiencing difficulties connecting JavaScript with HTML

I'm encountering difficulty with implementing my JavaScript on my website. While it functions properly in this JS Fiddle, I am experiencing issues when trying to use it on my actual site. Below is how I have linked the JS on my site: <head> < ...

Aggregation involves extracting data from a nested array within another nested array

Currently, I am working on setting up a time series in mongodb and following this guide for schema design: here. Suppose, within a collection, each document has the following structure: { _id: '...', timestamp_minute: '2018-01-01T12:30: ...

Uh oh! AngularJS just threw an error: Uncaught TypeError - angular.service is not a function. It happened in taskService.js

I've run into some issues with AngularJS, even though I have imported all the necessary libraries. Specifically, I am encountering the following errors: Uncaught TypeError: angular.service is not a function at taskService.js:2 taskFactory. ...