is there a way to prevent repeating code in html I'm using bootstrap 4 collapse like 20 times in one page
You can use a function to repeat how many times you want to duplicate your element, in the following snippet I created a function that will clone .card
node using .cloneNode()
and iterate a number of times, then modify the ids and attributes using querySelector()
on the cloned node, here is a snippet for option A
:
function duplicateElement(selector, numOfDuplicates) { let element = document.querySelector(selector); for(let i = numOfDuplicates; i > 0; i--) { let newElement = element.cloneNode(true);
newElement.querySelector('#headingOne').id = `headingOne-${i}`; newElement.querySelector('#collapseOne').id = `collapseOne-${i}`; newElement.querySelector('#collapseTwo').id = `collapseTwo-${i}`; newElement.querySelector('#headingTwo').id = `headingTwo-${i}`; let toggleBtn = newElement.querySelector('[data-target="#collapseOne"]'); toggleBtn.dataset['target'] = `#collapseOne-${i}`; toggleBtn.setAttribute('aria-controls', `collapseOne-${i}`); let toggleBtn2 = newElement.querySelector('[data-target="#collapseTwo"]'); toggleBtn2.dataset['target'] = `#collapseTwo-${i}`; toggleBtn2.setAttribute('aria-controls', `collapseTwo-${i}`);
element.after(newElement); } }
duplicateElement('.card', 4);
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria- expanded="true" aria-controls="collapseOne"> Collapsible Group Item #1 </button> </h5> </div> <!-- Add mx-auto --> <div id="collapseOne" class="collapse show text-center mx-auto" aria-labelledby="headingOne" style="width: 300px;"> <div class="card-body"> <div class="card"> <div class="card-header text-center" id="headingTwo" style="width: 300px;"> <h5 class="mb-0"> <button class="btn btn-link collapsed text-center" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo" style="width: 300px;"> Collapsible Group Item #2 </button> </h5> </div> <div id="collapseTwo" class="collapse show" aria-labelledby="headingTwo"> <div class="card-body"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus wolf moon put a craft beer sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings farm- </div> </div> </div> </div> </div></div>
How to avoid repetitive code in HTML?
There are lot many options to achieve DHTML.
A basic example using JavaScript:
var details = [{ 'img': "http://simpleicon.com/wp-content/uploads/light-bulb-6.svg", 'lbl': "Product 1"}, { 'img': "http://images.clipartpanda.com/light-bulb-vector-png-9czEXKbbi.svg", 'lbl': "Product 2"}, { 'img': "http://images.clipartpanda.com/light-bulb-vector-png-light-bulb-7.svg", 'lbl': "Product 3"}];
var html = "";for (var i = 0, l = details.length; l > i; i++) { html += "<div class=\"img-container\">"; html += "<a href=\"#\">"; html += "<img src=\"" + details[i].img + "\">" + details[i].lbl + "</a>"; html += "</div>";}
document.getElementsByClassName('sale')[0].innerHTML = html;
.sale { border: 1px ridge grey;}.img-container { border: 1px dashed grey; margin: 3px; display: inline-block; padding: 3px;}.img-container img { width: 100px;}
<div class="sale"> <div class="img-container"> <a href="#"> <img src="1.png">Product1</a> </div> <div class="img-container"> <a href="#"> <img src="2.png">Product2</a> </div> <div class="img-container"> <a href="#"> <img src="3.png">Product3</a> </div> <div class="img-container"> <a href="#"> <img src="4.png">Product4</a> </div></div>
Avoid repeated HTML
It depends on the language you are using. If you want to do this strictly in HTML, see if your server supports shtml. If it does, you can use includes to read the file into another file.
<!--#include FILE="filename.html"-->
Avoid repeating html with a directive
You don't need to use a custom directive. If all you want to achieve is to be able to reuse some html you can always put it into another template and use it by ng-include
:
<ng-include src="'/templates/reusableComponent.html'"></ng-include>
Reducing repeated HTML code
A templating engine would be best but if you're not planning on having many different variables and relatively short code chunks then you could put the code in a template block then perform a replace on the variable names.
<script type="text/html" id="template">
<!-- I'm replacing blockwrapper with #value# because it's less
likely to cause a collision -->
<p class="#value#">Bunch of other code</p>
</script>
function createHTML(templateID, value) {
var html = document.getElementById(templateID).innerHTML;
html = html.replace(/#value#/g, value);
return html;
}
This will create a new set of HTML code from your "template" replacing all occurrences of "#value#"
with value
.
Related Topics
Vertically Center Text in a 100% Height Div
CSS Right Margin Does Not Work Inside a Div with Overflow Scroll
How to Combine Multiple CSS Rules
Post Request to Include 'Content-Type' and JSON
How to Restrict My Input Type="File" to Accept Only Png Image Files Not Working in Firefox
Print When Textarea Has Overflow
Draw Single Pixel Line in HTML5 Canvas
How to Put Table in The Center of The Page Using CSS
How to Display The HTML Code of a Webpage in a Batch File
Which Unit I Should Use in CSS When Designing a Web Page
HTML Span Align Center Not Working
Assign Variables to Child Template in {% Include %} Tag Django