Home > Blockchain >  How To Inject Element By Rereferencing div From index.html? Javascript
How To Inject Element By Rereferencing div From index.html? Javascript

Time:01-04

I can insert an element by using:

const init = function () {
    var div = document.createElement('div');
    div.innerHTML = '<b>HI!</b>';
    document.body.appendChild(div);
}
init();

however, I have an element which can be found on my index.HTML file and want to reference it, so that I don't create a new element, but rather use the one already in existence on my index.HTML and then inject it to the website.

   <div >
        <div >
            00:00:00
        </div>
    </div>

I want to reference watch and time and display it on the page, or in other words inject it into it.

CodePudding user response:

The easiest way to select individual elements is to assign an ID to the elements you want to select. You can assign an ID using <div id="some_id">. In your js file, you can reference these elements using document.getElementById.

Example:

//references the div with an id of "conainer_b"
const containerB = document.getElementById("container_b") ;
containerB.innerHTML = "hello there";
<div id="container_a">
  <div id="container_b">
    some text
  </div>
</div>

CodePudding user response:

Pretty easy to insert to an element, here is one simple way using your example HTML. I added some borders just to show what is where.

const init = function() {
  var div = document.createElement('div');
  div.innerHTML = '<b>HI!</b>';
  document.body.appendChild(div);
  insertIntoWatch("Cheese bits!");
}

function insertIntoWatch(newtext) {
  const newthing = document.createElement('b');
  newthing.textContent = newtext;
  document.querySelector(".watch").appendChild(newthing);
}
init();
.watch {
  border: solid red 1px;
  padding: 1rem;
}

.time {
  border: solid green 0.25rem;
}

.watch>b {
  border: solid 2px blue;
}
<div >
  <div >
    00:00:00
  </div>
</div>

  • Related