Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create elements, set attribute, use innerHTML, and appendChild with JS and DOM

I am writing a sample program in HTML/JS to demonstrate creating an array of user-defined objects (property/value), creating an element, adding data from the object array using innerHTML, and then appending the newly filled element to print it using appendChild();

For some reason, running the program provides no output besides what I hard-code as debugging. View source is also not very helpful given the language.

Please forgive me for the simple question, I am new to JS and have spent many hours reading many resources - I feel I am probably missing something small.

Thank you!!

<title>
This is my title.
</title>

<body>
<p>xXx<br/></p>
<script>

var array = new Array();

var thing1 = {
property: "value-1"
};

        var thing2 = {
        property: "value-2"
        };


        array.push(thing1);
        array.push(thing2);

        for (index = 0; index < array.length; ++index) {

            test_el = document.createElement("p");

            test_el.innerHTML(array[index].property);

            document.body.appendChild(test_el);

        };
        //I wish to print 'value' text into the body from my object, that is all

</script>
</body>
like image 745
BenP Avatar asked Jan 11 '19 21:01

BenP


People also ask

What is the best way to create a DOM element set innerHTML or use createElement *?

#1) createElement is more performant However, using the innerHTML causes the web browsers to reparse and recreate all DOM nodes inside the div element. Therefore, it is less efficient than creating a new element and appending to the div.

How do I create an innerHTML element?

To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.

Which attribute do you use to replace innerHTML in DOM?

dangerouslySetInnerHTML is an attribute under DOM elements in React. According to the official documentation, dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM.

Which DOM method is used to create a new attribute?

HTML | DOM createAttribute() MethodsetAttribute() method is used to create a new attribute for an element.


1 Answers

Your error seems to be with innerHTML, that is not a function, so you should put that value equal to something. I have corrected your code so you can see the result.

var array = new Array();
var thing1 = {
  property: "value-1"
};
var thing2 = {
  property: "value-2"
};

array.push(thing1);
array.push(thing2);

for (index = 0; index < array.length; ++index) {
  test_el = document.createElement('p');

  test_el.innerHTML = array[index].property;

  document.body.appendChild(test_el);
};
<title>
  This is my title.
</title>

<body>
  <p>xXx<br/></p>
</body>
like image 74
Pietro Nadalini Avatar answered Sep 23 '22 18:09

Pietro Nadalini