简体   繁体   中英

JavaScript adding text after pageloads in a paragraph

HTML(can't change this):

<fieldset>
   <legend>Question 8</legend>
      <p>
        Create a new "p" element with the text "New Element", and add it to #question-8
      </p>
      <div id="question-8"></div>
    </fieldset>  

JavaScript:

var node = document.createElement('p');
node.setAttribute('id', 'q8');

var content = document.createTextNode("New Element");
node.appendChild(content);

console.log(node);

I am trying to get the text New Element to show up in a paragraph with the ID of q8. I must use non-obtrusive JavaScript. In my console window it shows up correctly, but it does not sow up in my HTML. How do I get it to appear?

Something close to this should work.

The code will only run once the whole document is loaded.

It will get the element in question by its id, then append a paragraph element to it, which in turn gets a text node with the desired content appended.

Since appendChild returns the child node we need to get its parentElement to pass to the upper appendChild call.

document.addEventListener('readystatechange', function(event) {
    if (event.target.readyState !== "complete") {
        return;
    }
    document.getElementById('question-8')
    .appendChild(document.createElement('p')
    .appendChild(document.createTextNode('New Element')).parentElement);
}, false);

It's probably easiest to do this:

var doc = document, bod = doc.body; // never use document or document.body again
function E(e){
  return doc.getElementById(e); // never use document.getElementById() again
}
E('question-8').innerHTML = "<p id='q8'>New Element</p>";

Of course, you could do this:

var doc = document, bod = doc.body;
function E(e){
  return doc.getElementById(e);
}
function C(t){
  return doc.createElement(t);
}
var q8 = C('p'), txt = doc.createTextNode('New Element'), qest8 = E('question-8');
q8.id = 'q8', q8.appendChild(txt); quest8.appendChild(q8);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM