innerHTML does not work when showing Tweet content - javascript

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>

Related

How to turn string into HTMLCollection

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);

Adding div tag below another div tag

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);

Simple GetElementById issue

I'm new to javascript I'm having a very simple problem. I just don't get what's going on.
I just want to add a class to a <div> tag but it's not working
This is my javascript:
var element = document.getElementById("main");
element.classList.add("hidden");
Here's my fiddle:
http://jsfiddle.net/72o6j6r0/
You are close, the method document.getElementById() returns an HTML element by using the id of the element
HTML:
<html>
<body>
<div id="main">
This is my main content to be hidden
</div>
</body>
</html>
Javascript:
var element = document.getElementById("main");
element.classList.add("hidden");
If you want to use the class attribute to select your elements rather than the id you can use:
document.getElementsByClassName()
and then loop over the results
Here is a JSFiddle example:
http://jsfiddle.net/mko3uf9f/

Jquery remove element from var

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);

does innerHTML get rid of elements entirely?

EDIT: I figured it out, thanks for your time!
I have a div with an id of container and three buttons above that.
When a user clicks any of the buttons above, then javascript replaces the contents of the div according to the buttons pressed using innerHTML.
Clicking on each button once works fine because I'm just replacing the elements in the div. But when I try to reclick the buttons my console prints out 'Uncaught TypeError: Cannot read property 'innerHTML' of null '
So I'm assuming innerHTML gets rid of the elements entirely. Is there a way to retrieve those elements so I can constantly click the buttons and have the respective elements appear?
If not, I was thinking of having a div for each button in my html file and then using display:none. When a user clicks on any of the buttons, the div for that button will be set to display:block.
***Edit****. I believed I answered my own question.**
Yes, using innerHTML does get rid of previous elements inside the div container. Therefore, if you wanted to grab those elements again, you can't. and the above error will be printed in the console.
JsFiddle : http://jsfiddle.net/7Q4vD/
<div id="buttonNav">
<button id="button1">1</button>
<button id="button2">2</button>
<button id="button3">3</button>
</div>
<div id="container">
<p id="para">Data in paragraph</p>
</div>
I Tried the following, and it worked perfect, check it:-
<button type="button" id="red"onclick="myFunction(id)"> Red!</button>
<button type="button" id="blue"onclick="myFunction(id)"> Blue!</button>
<button type="button" id="green"onclick="myFunction(id)"> Green!</button>
<div id="container"></div>
<script>
function myFunction(e){
document.getElementById('container').innerHTML = e
}
</script>
Ok, now got the problem.
You're writing:-
<div id="container">
<p id="para">Data in paragraph</p>
</div>
and then,
var container = document.getElementById('container');
and then you're setting the innerHTML with a sring:-
container.innerHTML = data;
So, suppose data = "abc";
The your html becomes
<div id="container">
abc
</div>
So, the p tag is not present here.
Thus when you're try the following in the next time:-
document.getElementById('para').innerHTML = data2;
It's not getting anything and showing the error.
Either you replace
document.getElementById('para').innerHTML = data2;
with
container.innerHTML = data2;
And remove the p tag from your html, or write:-
var para= document.getElementById('para');
and then write the following in respective cases:-
para.innerHTML = data2;
para.innerHTML = data;

Categories

Resources