James
James

Reputation: 33

Basic Help On inserting arrays in javascript into paragraph element in HTML

I have this simple html:

<h3 id='target'>
   <p> <!--insert javascript joined array here ---> </p>
</h3>

And this simple Javascript:

var letters = ["a", "b", "c", "d"];

var joinedLetters = letters.join(", and ");

var getElement = document.getElementById("target").firstElementChild;

getElement.innerHTML = joinedLetters;

PROBLEM:

It comes out formatted in h3 (text bold) and not p. My object is to insert the joined array in the paragraph element. I don't know if it's possible. Any help/explanation is appreciated. Thanks!

UPDATE:

I usually catch that mistake, but I guess not that time. Thanks all! I made all the necessary changes:

<h3>Joined</h3>
<p id='target'><!--insert joined array here--></p>

And the JS (not including the array JS above). This seems to be the outcome I wanted:

var getElement = document.getElementById("target").innerHTML;
document.write(getElement = joinedLetters);

CURIOUS:

How come if I write the code above like this, a duplicate of the array will appear?:

var getElement = document.getElementById("target");
document.write(getElement.innerHTML = joinedLetters);

And, it seems that the inserted array is not editable by CSS (all links established):

p {color: red}

I'm thinking it has something to do with the document.write function. Thanks once again! Great help, great help! :)

FINAL ANSWER:

var getElement = document.getElementById("target");
getElement.innerHTML = joinedLetters;

This house is clean.

Upvotes: 1

Views: 1223

Answers (2)

gffbss
gffbss

Reputation: 1701

As dandavis said, your p tag is wrapped in an h3 tag, meaning that that specific p tag will inherit the styling elements of it's parent tag in this case the h3. You can add the id 'target' to the p tag and remove the h3 as well as the firstElementChild in your document.get.

Upvotes: 1

davidcondrey
davidcondrey

Reputation: 35983

The paragraph is bold because it's wrapped in an H3 tag. Either get rid of the H3 tag or write some CSS like

h3#target > p { font-weight:400; }

Not sure if you were trying to retain the quotes in your output but you can do that as well like this..

var joinedLetters = "'" + letters.join("','") + "'";

// 'a','b','c','d'

Upvotes: 2

Related Questions