I have static html stored in javascript string literal templates.
On button click, (modal popup) I need to pass the stored static html through a function and update elements in it with dynamic data that gets stored in a hidden div.
I need the html static string to become a HTML Collection, so I can perform jQuery functions on it for finding and replacing elements in it with the dynamic content stored in the hidden divs.
How do I do that?
var htmlString = "<div class='abc'><p>Lorem <strong>ipsum</strong> dolor sit amet..</p></div>";
var html = $(htmlString);
It creates an element wrapped in jQuery, so you can perform it's methods on it and when you're finished, you can append() it to your modal.
Let's say var HTMLAsString = "<div id="dynamicDivId">This is paragraph</div>" is the HTML which you want to add to modal
<div id="modalDivId">
<div id="hiddenDivId">some data</div>
</div>
To get following output
<div id="modalDivId">
<div id="hiddenDivId">some data</div>
<div>some data</div>
</div>
You can do something like this
var dynamicDivSelector = $(HTMLAsString);
dynamicDivSelector.text($("#hiddenDivId").text());
$("#modalDivId").append(dynamicDivSelector);
To answer your question in the comments as to how to accomplish this in plain JavaScript, you'd need to do the following:
var newDiv = document.createElement('div');
newDiv.className = 'foo';
var markup = '<p>blah blah blah...</p>';
newDiv.innerHTML = markup;
You can then do whatever you need to do with the new node, and insert it to the DOM with something like:
document.body.appendChild(newDiv);
Related
I have a div tag with class divstudent, lets say this is div1 tag. Now I want to create another div tag div2 dynamically below this div1 tag, not inside of the div1 tag. I want to create outside of div1 tag using javascript. How can I do that?
"div1"
<div class="divstudent"></div>
<!-- i want to be like this -->
<!-- "div1" -->
<div></div>
<!-- "div2" -->
<div></div>
<!-- "div3" -->
<div></div>
$(function() {
$("div").eq(0).after("<div>This is div 2</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
This is div 1
</div>
Try something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Divs creator</title>
<script type="text/javascript">
window.onload = function () {
var divReference = document.querySelector('.divstudent');
var divCounter = 0;
divReference.addEventListener('click', function () {
var divToCreate = document.createElement('div');
divToCreate.innerHTML = ++divCounter;
divReference.parentNode.appendChild(divToCreate);
}, false);
}
</script>
</head>
<body>
<div class="divstudent">
<input type="button" value="add div below divstudent">
</div>
</body>
</html>
Since this is tagged jquery, just use .after()
$(function() {
$("div").eq(0).after("<div>This is div 2</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
This is div 1
</div>
There are many ways to do this. One significant difference in methods is if you choose to create the elements first using Document.createElement() and then insert the elements, or create and insert the elements in one step using one of the methods that allows you to insert HTML text.
Because it is simpler, but not necessarily better, the examples below show creating and inserting the two <div> elements in a single step using methods that allow inserting HTML text into the DOM.
JavaScript:
One is to use insertAdjacentHTML() and specify that it is to be inserted afterend of the element you are using.
document.querySelector() is used to find the first <div class="divstudent">. Then insertAdjacentHTML() is used to add the additional <div> elements. Element.removeAttribute() is then used to remove the class="divstudent". Note: if we had just wanted to set teh class to something different, even '', then we could have used Element.className.
NOTE: In this answer, text identifying each <div> has been added to the <div>s so there is something visible in the examples in this answer.
//Find the first <div class="divstudent"> in the document
var studentDiv = document.querySelector('div.divstudent');
//Insert two new <div> elements.
studentDiv.insertAdjacentHTML('afterend','<div>2</div><div>3</div>');
//Remove the class="divstudent"
studentDiv.removeAttribute('class');
<div class="divstudent">1</div>
jQuery:
While your question is tagged jQuery, a comment you posted implies you are just using JavaScript. Thus, I am not sure if jQuery works for you.
If you want to use jQuery, then you can use .after() to add the <div> elements. You can then use .removeAttr() to remove the class="divstudent".
// Get the first <div class="divstudent">.
// Store it in a variable so we only walk the DOM once.
var $studentDiv = $('div.divstudent').eq(0);
//Add the two new <div> elements
$studentDiv.after('<div>2</div><div>3</div>');
//Remove the class="divstudent"
$studentDiv.removeAttr('class');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divstudent">1</div>
You create a new div (in js), then just append your newDiv, after the target div. Something along the lines of in vanilla js:
// Create your new div
var newDiv = document.createElement("div");
newDiv.innerText = "New Div!";
// Grab the div you want to insert your new div after
var target_div = document.querySelector("div.divstudent");
// Insert newDiv after target_div (before the thing after it)
target_div.parentNode.insertBefore(newDiv, target_div.nextSibling);
In Html file, I test showing tweet content with
<div class="container" id="trackingResults">
<p id="printout">
<blockquote class="twitter-tweet" data-link-color="#55acee" lang="es">
<a href="https://twitter.com/jack/status/20">
</a>
</blockquote></p>
</div>
it works well
result1
then when i try to generate the content with js function
var trackingResults = document.getElementById('printout');
trackingResults.innerHTML = '<blockquote class="twitter-tweet" data-link-color="#55acee" lang="es"></blockquote>';
It does not work,
result2
Basically, I just copied same content to innerHTML property, but it shows the different results.
I do not know why.
As far as I understand, you are using Twitter api which convert your blockquote to properly formatted twitter tweet iframe, which works on page load event. And on changing innerHTML it does not work because that library do not bind on the newly added code. Due to which you are seeing nothing.
You should try creating an element using
Document.createElement()
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
fiddle
try
$('#trackingResults').html('<blockquote class="twitter-tweet" data-link-color="#55acee" lang="es"></blockquote>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="trackingResults">
</div>
I have a page with a parent div and several child divs. These are generated dynamically. I need to save the structure (html code) of all the child divs in my database, so I get the html content using .html().
But before I save the content in db, I need to remove one or more child divs. (But these divs will still need to be on the browser page)
How do I use the remove method with the selector (in this example I need to remove child3) on the output of .html()
<div id="graph-parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
<div id="child5"></div>
</div>
var htmlContent = $( "#graph-parent" ).html();
how do I remove child3 from htmlContent?
Simply clone the element and operate on that:
var clone = $('#graph-parent').clone();
clone.find('#child3').remove();
var htmlContent = clone.html();
I think you need something like this:
http://jsfiddle.net/glegan/65QPV/
var clone = $('#graph-parent').clone();
clone.find('#child1').remove();
clone.find('#child5').remove();
var htmlContent = clone.html();
alert(htmlContent);
I have to convert plain text urls to . I've found a JS code that works. My problem is that my HTML structure needs that I modify the code, putting the current code inside a foreach.
My html:
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
<div class="content">Some text with links</div>
The JS:
$(function()
{
var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/ig;
$('.content').html($('.content').html().replace(re, '$1'));
});
The above JS works, but will populate all the div's with the same content. I've tried to put this code in a foreach but have failed. My poor JS knowledge makes me ask this on SO.
Can you give some clues on how to put this code in a foreach loop?
Functions like .html allow a function to be passed. An .each loop is then done internally, and moreover you get the current value passed:
$('.content').html(function(i, current) {
return current.replace(re, '$1');
});
.html() for retrieval only selects the first matched element. You can do this pretty easily, though, because functions like .html can take a function argument for setting that iterates over each selected element individually.
$(".content").html(function (_, html) {
return html.replace(re ...etc...);
});
If I've understood your question correctly, you need to loop through each .content div, try this:
$('.content').each(function() {
var $content = $(this);
var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/ig;
$content.html($content.html().replace(re, '$1'));
});
I'd like to get the text from between the "p" tags and put it in an other element, like this:
before:
<div id="Text">
<p>$1,200.00</p>
</div>
<div id="putText">
<p></p>
</div>
after:
<div id="Text">
<p>$1,200.00</p>
</div>
<div id="putText">
<p>$1,200.00</p>
</div>
Anyone know of a Javascript that can do this?
The below function copies the contents of the first paragraph under an element with ID ID to a paragraph under another element with ID putID.
function copyContents(id) {
var source = document.getElementById(id).getElementsByTagName("p")[0];
var target = document.getElementById("put" + id).getElementsByTagName("p")[0];
target.innerHTML = source.innerHTML;
}
copyContents("Text");
you can use following jQuery code
$('#putText p').html($('#Text p').html());
If you have jQuery at your disposal, it's fairly easy - something like this should work:
$('#putText>p').text($('#Text>p').text())
If you don't, then you'll have to resort to some DOM manipulation - the same stuff jQuery does behind the scenes, only you need to code it up yourself.