Insert HTML code to div onClick but does not replace existing code - javascript

I would like to insert HTML code to make a "list". I've seen examples of innerHTML but that just replaces the existing code. How can I add more code without replacing the current code?
var addTo = document.querySelector(".activePage")[0];
var addHTML = '
<div id="item1">
<h1>This is a heading</h1>
<p>This is a paragraph</p>
</div>'
addTo.innerHTML(addHTML)'
<nav class="activePage"><nav>

Use insertAdjacentHtml. Docs - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML.
var addTo = document.querySelector(".activePage");
var addHTML = '<div id="item1"><h1>This is a heading</h1><p>This is a paragraph</p></div>
addTo.insertAdjacentHtml(addHTML, 'beforeEnd')
'beforeEnd' means it will add right before the end of the element(inside the element).

You have to append to the HTML inside the nav tag instead of replace it with a new value.
var addTo = document.querySelector(".activePage");
var addHTML = '<div id="item1"><h1>This is a heading</h1><p>This is a paragraph</p></div>';
addTo.innerHTML += addHTML;
<nav class="activePage">
<nav>

Add your HTML to the existing HTML inside of the target element using +=.
function addNew() {
var addTo = document.querySelectorAll(".activePage")[0];
var addHTML = '<div id="item1"><h1>This is a heading</h1><p>This is a paragraph</p></div>'
addTo.innerHTML += addHTML
}
<nav class="activePage">
<button onclick="addNew()">add</button>
<nav>

I believe what you're after is the append feature.
https://api.jquery.com/append/
or
https://www.w3schools.com/jsref/met_node_appendchild.asp
Below is a jquery example. I have used this example as i think it's easier to understand what's going on at first glance
example:
$(".your_div").append(html_load());
function html_load() {
return '<li class="list"> list item </li>'
}
This will result in the below:
<div class="your_div">
<li>start</li>
</div>
being updated to:
<div class="your_div">
<li>start</li>
<li class="list"> list item </li>
</div>

Related

JavaScript: Dynamically created html-like string won't tun into html

in DOM I already have a wrapper
<div id="wrapper"></div>
which I need to fill with bunch of divs, where each will represent new category.
Each category will be then filled with various cards representing items of that category. Like this:
<div id="wrapper">
<div data-category="puppy">
Dynamically created category wrapper
<div class="puppy1">...</div>
<div class="puppy2">...</div>
</div>
<div data-category="cat">
...
</div>
</div>
I use following code to create and fill category, but I always end up either having empty category or having a string inside reprenting the html.
var categoryWrapper = document.createElement("div");
categoryWrapper.setAttribute("data-category", key);
categoryWrapper.innerHtml = htmlString;
Here is a fiddle demo of my issue.
https://jsfiddle.net/uuqj4ad5/
I'll be grateful for a help.
There is a typo, innerHml should be innerHTML(Javascript object properties are case sensitive) otherwise it simply add an additional property and nothing gets happened.
categoryWrapper.innerHTML = htmlString;
var htmlString = "<div class='card'><div class='cardImg'><img src='http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg' alt='Puppy'></div><div class='cardContent'><div class='cardInfo'><p>Puppy Yawning</p></div><div class='cardDesc'><p>Awww!</p></div></div></div>";
var outerWrapper = $("#wrapper");
var categoryWrapper = document.createElement("div");
categoryWrapper.innerHTML = htmlString;
outerWrapper.append(categoryWrapper);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>
Under this title various categories should be dynamically created
</h3>
<div id="wrapper">outerWrapper waiting for dynamic data...</div>
</div>
FYI : If you want to remove the existing content then use html() method instead of append() method.
innerHtml
should be
innerHTML
Javascript is case sensitive
If you are using jQuery why do you want to mix jQuery and Vanilla JS.
var outerWrapper = $("#wrapper");
// I created new categoryWrapper object
var categoryWrapper = $('<div/>', {
html: htmlString
});
debugger;
// WHen I have the category filled with inner data, I will append it into outerwrapper
outerWrapper.append(categoryWrapper);
jsFiddle
Checkout my fiddle:-
https://jsfiddle.net/dhruv1992/1xg18a3f/1/
your js code should look like this
// This is dynamically filled html template. The data comes from some JSON.
var htmlString = "<div class='card'><div class='cardImg'><img src='http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg' alt='Puppy'></div><div class='cardContent'><div class='cardInfo'><p>Puppy Yawning</p></div><div class='cardDesc'><p>Awww!</p></div></div></div>";
// This outer wrapper will in the end contain few categories
var outerWrapper = $("#wrapper");
outerWrapper.append('<div>'+htmlString+'</div>')

replace set of strings in array

Using $('div#top_container').html(), I get the following as an example:
<div class="top" id="top_container">
<div class="example">First</div>
<div class="example">Second</div>
</div>
giving...
<div class="example">First</div>
<div class="example">Second</div>
Here, using .replace(), I want to replace <div class="example"> with *%^% (random set of characters) and remove </div>:
var content = $('div#top_container').html();
var clean_1 = content.replace('<div class="example">','*%^%'); //add $*!#$
var clean_2 = clean_1.replace('</div>',' '); //remove </div>
giving...
console.log(clean_2); --> *%^%First*%^%Second
Now, the number of example div elements can vary and I need to first find out how to target them all. Also is there a cleaner way to target both <div class="example"> and </div> at the same time?
EDIT:
I am not looking to change the html itself, but rather have the edited version as a variable that I can do stuff with (such as send it to php via ajax).
How would I do this?
Use replaceWith() method with a callback and generate prefered text string by getting text content using text() method.
$('div.example').replaceWith(function(v) {
return '%^%' + $(this).text();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="example">First</div>
<div class="example">Second</div>
</div>
UPDATE: If you don't want to update the original element then use clone() and do the remaining thinks on the cloned element.
var res = $('#parent')
// clone element
.clone()
// get element with `example` class
.find('.example')
// update content
.replaceWith(function(v) {
return '%^%' + $(this).text();
})
// back to previos selector and get html content
.end().html();
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div class="example">First</div>
<div class="example">Second</div>
</div>
Create one prototype like :
String.prototype.replaceAll = function (toReplace, replaceWith){
return this.split(toReplace).join(replaceWith);
}
and your jquery code be like :
$("div#top_container").each(function( i ) {debugger;
console.log(this.innerHTML.replaceAll('<div class="example">','*%^%').replaceAll('</div>',' ');)
});
You can use replaceWith function
$(function () {
$(".example").replaceWith(function(){
return "%^%"+$(this).text();
});
});
You can make a clone of container if you don't want to change original div.
var html="";
$(function () {
var newHtml = $("#top_container").clone();
$(newHtml).find(".example").replaceWith(function () {
html+= "%^%" + $(this).text();
});
});
console.log(html);

Replace HTML element with string content using native JS

There is the following HTML code:
<body>
<menu>
</menu>
... other html
</body>
I need to replace <menu> tag with HTML content from variable. I know how I can change innerHTML using string variable with content (variable 'template');
menu.innerHTML = template;
Variable 'template' contains '<ul class="menu"></ul>'. As result I want to have the following HTML:
<body>
<ul class="menu">
</ul>
... other html
</body>
You mention innerHTML; there's a corresponding outerHTML property that, when set, will replace the element and all children with your update:
var menu = document.getElementsByTagName('menu')[0];
menu.outerHTML = template;
Try:
var body = document.getElementsByTagName('body')[0];
body.innerHTML = body.innerHTML.replace(/<menu>[\s\S]*?<\/menu>/, template);
Try this
var str = '<ul class="menu"></ul>';
var menu = document.getElementsByName('menu');
var parentMenu = menu.parentNode;
parentMenu.removeChild(menu);
parentMenu.innerHTML = str + parentMenu.innerHTML;
try this
var elem = document.getElementsByTagName('body')[0]; // Select any element you want.
var target = elem.innerHTML;
elem.innerHTML = target.replace(/(<menu)/igm, '<ul class="menu"').replace(/<\/menu>/igm, '</ul>');

How to split multiple string using jQuery or javascript?

I know this been posted here: how to split the string using jquery or javascript
but in my case have multiple strings. It's working in a single line of string but if it's in a multiple lines it repeats the day after year. and for some reason it display's only the first 'li' value. Is it possible to display it this way:
<ul>
<li>
<div class="date">
<p class='day'>23</p>
<p class='month'>05</p>
<p class='year'>2013</p>
</div>
</li>
<li>
<div class="date">
<p class='day'>25</p>
<p class='month'>07</p>
<p class='year'>2014</p>
</div>
</li>
<li>
<div class="date">
<p class='day'>01</p>
<p class='month'>05</p>
<p class='year'>2014</p>
</div>
</li>
</ul>
here is my code:
html
<ul>
<li><div class="date">23-05-2013</div></li>
<li><div class="date">25-07-2014</div></li>
<li><div class="date">01-05-2014</div></li>
</ul>
css:
.day{color:#ccc;}
.month{color:#ff0000;}
.year{color:green;}
script:
var data =$('.date').text();
var arr = data.split('-');
$(".date").html("<p class='day'>"+arr[0]+"</p>"+"<p class='month'>"+arr[1]+"</p>"+"<p cass='year'>"+arr[2]+"</p>");
jsfiddle:
demo
thanks Bon
You are getting the text from the first element, and changes all elements to contain the code for that. You need to loop through the elements and convert the content in each one.
You can use a callback function in the html method to do that, it will get the original HTML code from each element, and you return the new HTML code for that element:
$(".date").html(function(i, h) {
var arr = h.split('-');
return "<p class='day'>"+arr[0]+"</p><p class='month'>"+arr[1]+"</p><p class='year'>"+arr[2]+"</p>";
});
Demo: http://jsfiddle.net/Guffa/815c95jn/1/
(Note the difference in function, as this will get the HTML code in each element instead of the text. As long as there is no actual HTML markup in the elements, like in your example, there is no difference in the result.)
An alternative to splitting the text is to use replace:
$(".date").html(function(i, h) {
return "<p class='day'>" + h.replace("-", "</p><p class='month'>").replace("-", "</p><p class='year'>") + "</p>";
});
You only selected one .date, but you have to iterate over all of them, e.g. using $.each():
$(".date").each(function () {
var data = $(this).text();
var arr = data.split('-');
$(this).html("<p class='day'>" + arr[0] + "</p>" +
"<p class='month'>" + arr[1] + "</p>" + "<p class='year'>" + arr[2] + "</p>");
});
Adjusted Fiddle, and for reference: http://api.jquery.com/each/
Since the title asks about how to completed this with jQuery or Javascript (assuming vanilla JS) let me give a quick example of how this might be done without the need for jQuery:
var dates = document.querySelectorAll('.date');
var dateClasses = ['day', 'month', 'year'];
Array.prototype.forEach.call(dates, function(date){
var dateString = date.innerHTML;
var dateStringArray = dateString.split('-');
var content = "";
for(var i = 0; i < dateStringArray.length; i++){
var newDate = document.createElement('p');
newDate.classList.add(dateClasses[i]);
newDate.innerHTML = dateStringArray[i];
content += newDate.outerHTML;
}
date.innerHTML = content;
});
.day{color:#ccc;}
.month{color:#ff0000;}
.year{color:green;}
<ul>
<li><div class="date">23-05-2013</div></li>
<li><div class="date">25-07-2014</div></li>
<li><div class="date">01-05-2014</div></li>
</ul>

Input data from table of arrays into list

I've got a list and I want to input a data from it by the table of arrays and I don't have idea how .
Here is the code and my attempts:
HTML:
<body>
<div class="top-menu style4"style="margin-top:300px;">
<ul class="top-menu-main">
<li>
<ul class="top-submenu">
<li><a class="up_items"style="padding-top:5px;">SEMINARS</a></li>
<li><a class="up_items"style="padding-top:5px;">STATUTES</a></li>
<li><a class="up_items"style="padding-top:5px;">RÉSUMÉ</a></li>
<li><a class="up_items"style="padding-top:5px;">ADR & PPCs</a></li>
<li><a class="up_items"style="padding-top:5px;">PREPARATIONS</a></li>
<li><a class="up_items"style="padding-top:5px;">MUSINGS</a></li>
<li><a class="up_items"style="padding-top:5px;">GLOSSARY</a></li>
<li><a class="up_items"style="padding-top:5px;">AWARDS</a></li>
</ul>
<a style="width:100px;text-align:center;text-align:center;font-family:arial;font-size:0.7em;font-weight:bold;border-top:none;">START</a>
</li>
</ul>
</div>
</body>
I've tried to do something with this script but what i got is a simple list without any slide, css elements and so on which i included in my code ..
JS:
<script type="text/javascript">
function makeMenu() {
var items = ['Start','Trident','Internet Explorer 4.0','Win 95+','5','5'];
var str = '<ul><li>';
str += items.join('</li><li>');
str += '</li></ul>';
document.getElementById('jMenu0').innerHTML = str;
}
window.onload = function() { makeMenu(); }
$(document).ready(function(){
$("#jMenu").jMenu();
})
</script>
There are some mistakes in your code.
Use the same jQuery ready function to load menu.
Use .class selector or #id to select the menu.
Don't include two times the UL tag.
Here is your code working:
function makeMenu() {
var items = ['Start','Trident','Internet Explorer 4.0','Win 95+','5','5'];
var str = '<li>';
str += items.join('</li><li>');
str += '</li>';
$('.top-menu-main').html(str);
}
$(document).ready(function(){
makeMenu();
$(".top-menu-main").menu();
});
You can check it here:
http://jsbin.com/irasof/1/edit
You haven't assigned an id to your unordered list.
the call
$("#jMenu").jMenu();
expects to find an element with the id jMenu.
Try adding that id in your js function
var str = '<ul id\"jMenu\"><li>';
take a look at the docs of that plug-in
And the line
document.getElementById('jMenu0').innerHTML = str;
tries to add the generated HTML inside an element with the id jMenu0. The HTML code you are showing does not contain such an element. You need to add it first, maybe somthing like that will be enough
<div id="jMenu0" />

Categories