Pass html file as the value of innerHTML

905 views javascript
9

I am calling a function that replaces innerHTML of a div when a user clicks on a particular div. I am able to pass raw html code inside the function to achieve the desired result but I want to use the same function to dynamically replace the content of different divs depending on which div was clicked.

For instance if div1 was clicked then the innerHTML should be replaced with a div1.html file and div2 with div2.html file. I coming from a PHP background and just learning vanilla javascript so I'm wondering how this can be done.

Here's some sample code I playing around with

function jobDescription() {
    document.getElementById('details').innerHTML = "\
        <div class=\"col-12 fade show\">\
            <div class=\"card text-white bg-dark\">\
                <div class=\"card-body text-center\">\
                    <h4 class=\"card-title\">Fullstack Web Developer</h4>\
                    <p class=\"card-text\">REMOTE</p>\
                </div>\
            </div>\
        </div>\
    ";
}
<div id="details" class="row align-items-center mt-5">
  <div id="freelance" class="col-lg-4 col-md-6 mb-3" onclick="jobDescription()">
      <div class="card text-white bg-dark">
          <div class="card-body text-center">
              <h4 class="card-title">Backend Web Developer</h4>
              <p class="card-text">FREELANCE</p>
          </div>
      </div>
  </div>
</div>

answered question

Check out github.com/patrick-steele-idem/morphdom which does eaxactly what you need, and it's blazing fast.

Btw, make yourself familiar with ES6 template literals, it saves you alot of headache with regard to concatenating/escaping HTML.

1 Answer

12

For this you can use the concept of iframes.

function FuncDesc(id, val)
{	alert(val);document.getElementById('i'+id).src = val;	}
<!DOCTYPE html>
<html>
<head>
	<title></title>
<script type="text/javascript">

</script>

</head>
<body>
<div id ="div1" onclick="FuncDesc(this.id, 'div1.html')">Div1</div>
<div id ="div2" onclick="FuncDesc(this.id, 'div2.html')">Div2</div>

 <iframe id="idiv1"></iframe> 
 <iframe id="idiv2"></iframe> 
</body>
</html>

posted this

Have an answer?

JD

Please login first before posting an answer.