3

I've created the below function to dynamically create HTML elements and append them wherever I want. The console doesn't log any errors when it runs, but the second element (<p>) doesn't write to the document.

I'm thinking the error is something related to the "createdDiv" variable, but I haven't been able to isolate what is going wrong.

Any help would be greatly appreciated!

//Array of elements to be created

var createdElements = [
    [ 'div', 'Class0', 'ID0'],
    ['p', 'Class1', 'ID1']      
];


//function to create and append elements to document

function createHTML( typeOfCreatedElement ,createdElementClass, createdElementId, locationForCreatedElement ){
    var createdElement = document.createElement( typeOfCreatedElement );
    createdElement.className = createdElementClass;
    createdElement.id = createdElementId;

    locationForCreatedElement['appendChild']( createdElement );

    return createdElement;
}


//run function 2x; 
//createdDiv successfully writes to the document, but createdParagraph disappears into a black hole...

var createdDiv = createHTML( createdElements[0][0], createdElements[0][1], createdElements[0][2], document.body );
var createdParagraph = createHTML( createdElements[1][0], createdElements[1][1], createdElements[1][2], createdDiv );
2
  • Could you please formulate a jsfiddle? :) Commented Dec 12, 2015 at 17:55
  • Actually your code seems to work as it is. To see the paragraph on a page, you need to add some content to it. Commented Dec 12, 2015 at 18:18

1 Answer 1

1

can you try with this update createHTML method()

function createHTML( typeOfCreatedElement ,createdElementClass, createdElementId, locationForCreatedElement ){
    var createdElement = document.createElement( typeOfCreatedElement );
    createdElement.className = createdElementClass;
    createdElement.id = createdElementId;
    createdElement.innerHTML = "this is a sample text for element type " + typeOfCreatedElement;

    locationForCreatedElement.appendChild( createdElement ); //line that I have changed.

    return createdElement;
} 

appendChild is a method, not a property.

Sign up to request clarification or add additional context in comments.

4 Comments

OP seems to use appendChild like a method in their code. Using dot notation instead of bracket notation doesn't change anything.
I added a fiddle link in my comment to OP's post. Their code seems to work.
@Teemu okay, I have added the innerHTML property as per your suggestion in your comment. All credit to you for detecting this.
Hey! Where is my credit, I haven't got anything ; ). Just a joke, inresponsive questionnaires are a sort of a plague at SO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.