When I reload my browser to show some json data the JavaScript code keeps replacing my HTML code? How can I correct the problem?
JavaScript code:
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
document.write(data.title);
};
HTML Code:
<div class="container">
<div id="json_example">
<h1>json Example</h1>
</div>
</div>
Don't use document.write() as it replaces fully built HTML documents with the new content. document.write() should only ever be used to construct dynamic pages while the page is being built.
Instead, just populate some pre-existing element with data.title,
As in:
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
$("#output").text(data.title);
};
<div class="container">
<div id="json_example">
<h1>json Example</h1>
<span id="output"></span>
</div>
</div>
You are using document.write() which takes your document, and replaces it's content with the content you supply to the function. If you want to replace just the content of the <div id="json_example"></div> element, then you can use the following snippet in place of the document.write():
$("#json_example").text(data.title);
For non jQuery-version:
document.querySelector("#json_example").innerText = data.title;
If you want to replace the content of the <h1> the correct selector would be #json_example h1 instead.
In all the snippets what you do is find the element you want to change the content of using a CSS-selector. Both jQuery and pure Javascript supports this since IE8.
After finding the correct element, you set the elements content text to the content you want.
NOTE! Do NOT use innerHtml or .html() to set the content, as that opens you to script injections. Only use those methods when you generate the HTML yourself on the fly, in the browser. Even your database needs to be considered dirty.
try this
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
document.getElementById("json_example").textContent = data.title;
};
Since you're already using jQuery here's a possible solution which uses it.
$.getJSON('https://jsonplaceholder.typicode.com/posts/1', function, data) {
$("#json_example").html("<h1>" + data.title + "</h1>");
};
This replaces your div html with your content.
Related
So, I am trying to load picture from another page using Jquery .load(), now the element I am trying to load has multiple children element which also load on current page, now obviously I could hide those divs but first I want to know if there's way to only grab parent div and leave out children.
I have tried using parent() method but since .load() works differently, it didn't work as intended. (Unless I missed something)
$('#myNewDiv').load('/robots .heading-image');
Here's HTML code from the other page
<div class="heading-image" style="background-image:url(imagelinkhere.png)">
<div class="heading-image_cover">
<div class="left">
<div class="heading-image title">Heading Title</div>
<div class="heading-image desc">I am a desc</div>
</div>
<div class="right">
<div class="heading-image stat">Stat text</div>
</div>
</div>
</div>
That's the code I am using right now, but .heading-image has multiple child elements as mentioned above.
To sum up, I need to load only parent element and ignore all child elements of the div mentioned above without having to load those children on current page and hide them (If possible)
From what I understand, your goal seems to be to copy the empty div to a new page, while maintaining the background image associated with the <div> tag.
The simplest approach would be to add to a stylesheet in which both of the pages can reach. For example:
CSS
.heading-image{
background-image:url(imagelinkhere.png);
}
JavaScript
$('#myNewDiv').html("<div class="heading-image"></div>");
Then in the head of both HTML documents, have <link rel="stylesheet" href="style.css"> to point towards the correct stylesheet for both pages.
If you just want the empty <div class="heading-image"></div> you could use the load() complete callback to empty it:
$('#myNewDiv').load('/robots .heading-image', function(){
// new html exists in page now, 'this' is #myNewDiv element
$(this).find('.heading-image').empty();
});
If there are resources inside that element like images, videos etc that you don't want to load in page you could also parse the :
$.get('/robots').then(function(html){
var $hImage = $(html).find('.heading-image').empty();
$('#myNewDiv').html($hImage)
});
With all that said I don't see why you need to extract an empty element from another page and can't just do:
$('#myNewDiv').html('<div class="heading-image"></div>')
I have a simple javascript code that dynamically adds HTML content to a div tag.
function addData(id,title,title_data){
var htmlcode='';
htmlcode+=`<h1> Title: `+title+` </h1> <div ng-app="">
<input ng-model="model`+title+id`" ng-init="model`+title+id+'='+\'`+title_data+`\'`" >`+
`<p ng-bind="model`+title+id`"> </p>`;
return htmlcode;
}
Then i simply use it like this:
$('#someDiv').html(addData(1,'Some Title','Some title data'));
The html works well and displays the desired dynamic content. But the angular bindings didn't work. The copy pasted version of the rendered html from web browser works well including the bindings but the dynamic one does not. What seems to be the problem?
You are not using the ng-app name in the declared dynamic html code.
I would like to insert a couple of opening DIV tags after the H1 element on a page, without inserting the corresponding closing tags (since the closing tags are contained in an included footer file which I don't have access to).
i.e.
Existing code:
<body>
<h1>Heading One</h1>
... page content...
</div>
</div>
</body>
New code:
<body>
<h1>Heading One</h1>
<div id="foo">
<div id="baa">
... page content...
</div>
</div>
</body>
DOM methods insert the div as a complete (closed) element, 'createTextNode' inserts escaped characters and 'innerHTML' needs an element to insert into. Have even tried to insert a script element with document.write without any luck.
Any ideas (jQuery would be fine)?
Update
The following worked:
document.body.innerHTML = document.body.innerHTML.replace('</h1>','</h1><div id="foo"><div id="baa">')
As pointed out by Asad the solution (which now seems obvious of course) is to use string methods on the HTML rather than DOM methods.
If you're dealing with DOM manipulation, use DOM manipulation methods. If you're dealing with HTML manipulation, use string manipulation methods.
h1.parentElement.innerHTML = h1.parentElement.innerHTML.replace("<h1>Heading One</h1>","<h1>Heading One</h1><div><div>");
i think this will answer your question, it is all about valid XML formation.
http://www.w3schools.com/xml/xml_syntax.asp
Forget DOM methods, insert it as a string using .replace().
Your approach is fundamentally wrong. The browser parses the DOM as it sees it, and automatically closes any tags that ought to be closed. It's impossible to use JavaScript to insert only the opening tag.
You say "the closing tags are contained in an included footer file which I don't have access to." Closed tags that haven't been opened are ignored, so as far as the DOM parser is concerned, those closing tags don't exist.
Your solution is either:
Put the opening tags in a header, or somewhere else on the server-side, or
Use JavaScript to grab ALL the following DOM elements, including the footer, and .wrap() them all in the desired divs.
This kind of practice seems a bit unorthodox, but perhaps something like this would help.
Existing HTML
<h1 id="testH1">Test H1</h1>
<div id="existingDiv">
<div id="existingDivContent">Existing Div Content</div>
</div>
New HTML
<h1 id="testH1">Test H1</h1>
<div id="newDiv">
<div id="existingDiv">
<div id="existingDivContent">Existing Div Content</div>
</div>
</div>
JS
The javascript is fairly rudimentary, but I think the concept can be applied to safely and properly achieve your goal.
$(document).ready(function() {
//-- parent node you wish to copy
var existingDiv = $('#existingDiv');
//-- new parent div node
var newDiv = $('<div id="newDiv">');
//-- where we want to insert the new parent node
var testH1 = $('#testH1');
//-- stuff our previous parent node into our new parent node
newDiv.html(existingDiv);
//-- insert into the DOM
testH1.after(newDiv);
});
http://jsfiddle.net/8qzvN/
Is there a way to store a HTML snippet in a variable using Javascript or jQuery like this? (obviously it's a non-working an example)
var mysnippet = << EOF
<div class="myclass">
<div class="anotherclass">
Some dummy text
</div>
</div>
EOF
And then insert it in the document using jQuery:
mysnippet.append($('#someelement'));
EDIT:
Please, read this before answering of commenting: What I have is a raw HTML snippet inside my JS file, and I need to store it in a Javascript variable using something like that EOF construction. I need to avoid putting it between quotation marks.
If it's not possible using Javascript and/or jQuery, then the question has no solution.
Just get the HTML code of the div you want by var content = $('#somediv').html(); and then append it to some div later on ! $('#otherdiv').append(content);
$().html(); delivers the HTML Content of that div. documentation: http://api.jquery.com/html/
$().append(<content>); appends the Content to a special div. documentatoin: http://api.jquery.com/append/
You could use javascript templates like ejs and haml-coffee.
You could write:
var mysnippet = "<div class='myclass'>"+
"<div class='anotherclass'>"+
"Some dummy text"+
"</div>"+
"</div>";
and then insert is using the append function (which takes the snippet as argument).
Yes. Fiddle example
JavaScript
var html = '<b>Bold</b>'
$('.anotherclass').append(html);
HTML
<div class="myclass">
<div class="anotherclass">
Some dummy text
</div>
</div>
Unfortunately nothing like << EOF is available. Here's one solution:
$el = $('<div />')
.addClass('myClass')
.append(
$('<div />')
.addClass('anotherclass')
.text('Foo Bar')
);
Thinking on the same issue I have found this discussion. What I have in mind is to put a hidden textarea, containing the html, and then retrieving the html from there.
Thus there will be no conflicts with doubled DOM ids, since textarea content isn't rendered as html.
For those who come across this as I have...
You may wish to use the new
<template>
tag in HTML5.
It still doesn't store the HTML in the JavaScript unfortunately :(
I'm hoping that this isn't too subjective. I feel there is a definitive answer so here goes.
I want to create this html on the fly using JS (no libraries):
Play
Mute
<div id="progressBarOuter">
<div id="bytesLoaded"></div>
<div id="progressBar"></div>
</div>
<div id="currentTime">0:00</div>
<div id="totalTime">0:00</div>
using javascript. I know I can do this using createElement etc but it seems extremely long winded to do this for each element. Can anyone suggest a way to do this with more brevity.
I do not have access to a library in this project....so no jquery etc.
Keep your markup separate from your code:
You can embed the HTML snippets that you'll be using as hidden templates inside your HTML page and clone them on demand:
<style type="text/css">
#templates { display: none }
</style>
...
<script type="text/javascript">
var node = document.getElementById("tmp_audio").cloneNode(true);
node.id = ""; // Don't forget :)
// modify node contents with DOM manipulation
container.appendChild(node);
</script>
...
<div id="templates">
<div id="tmp_audio">
Play
Mute
<div class="progressBarOuter">
<div class="bytesLoaded"></div>
<div class="progressBar"></div>
</div>
<div class="currentTime">0:00</div>
<div class="totalTime">0:00</div>
</div>
</div>
Update: Note that I've converted the id attributes in the template to class attributes. This is to avoid having multiple elements on your page with the same ids. You probably don't even need the classes. You can access elements with:
node.getElementsByTagName("div")[4].innerHTML =
format(data.currentTime);
Alternatively, you can act on the HTML of the template:
<script type="text/javascript">
var tmp = document.getElementById("tmp_audio").innerHTML;
// modify template HTML with token replacement
container.innerHTML += tmp;
</script>
Shove the entire thing into a JS variable:
var html = 'Play';
html += 'Mute';
html += '<div id="progressBarOuter"><div id="bytesLoaded"></div><div id="progressBar"></div></div>';
html += '<div id="currentTime">0:00</div>';
html += '<div id="totalTime">0:00</div>';
Then:
document.getElementById("parentElement").innerHTML = html;
if you want theN:
document.getElementById("totalTime").innerHTML = "5:00";
You can use
<script type="text/javascript">
function appendHTML() {
var wrapper = document.createElement("div");
wrapper.innerHTML = '\
Play\
Mute\
<div id="progressBarOuter"> \
<div id="bytesLoaded"></div>\
<div id="progressBar"></div>\
</div>\
<div id="currentTime">0:00</div>\
<div id="totalTime">0:00</div>\
';
document.body.appendChild(wrapper);
}
</script>
If you live in 2019 and beyond read here.
With JavaScript es6 you can use string literals to create templates.
create a function that returns a string/template literal
function videoPlayerTemplate(data) {
return `
<h1>${data.header}</h1>
<p>${data.subheader}</p>
Play
Mute
<div id="progressBarOuter">
<div id="bytesLoaded"></div>
<div id="progressBar"></div>
</div>
<time id="currentTime">0:00</time>
<time id="totalTime">0:00</time>
`
}
Create a JSON object containing the data you want to display
var data = {
header: 'My video player',
subheader: 'Version 2 coming soon'
}
add that to whatever element you like
const videoplayer = videoPlayerTemplate(data);
document.getElementById('myRandomElement').insertAdjacentHTML("afterbegin", videoplayer);
You can read more about string literals here
edit: HTML import is now deprecated.
Now with Web Components you can inject HTML using an HTML import.
The syntax looks like this:
<link rel="import" href="component.html" >
This will just load the content of the html file in the href attribute inline in the order it appears. You can any valid html in the loaded file, so you can even load other scripts if you want.
To inject that from JavaScript you could do something of the likes of:
var importTag = document.createElement('link');
importTag.setAttribute('rel', 'import');
importTag.setAttribute('href', 'component.html');
document.body.appendChild(importTag);
At the time I am writing this, Chrome and Opera support HTML imports. You can see an up to date compatibility table here http://caniuse.com/#feat=imports
But don't worry about browsers not supporting it, you can use it in them anyway with the webcomponentsjs polyfill.
For more info about HTML imports check http://webcomponents.org/articles/introduction-to-html-imports/
If you don't need any validation for your syntax (which is what makes createElement() so nice) then you could always default to simply setting the innerHTML property of the element you want to insert your markup inside of.
Personally, I would stick with using createElement(). It is more verbose but there are far less things to worry about that way.
If performance is a concern, stay away from innerHTML. You should create the whole object tree using document.createElement() as many times as needed, including for nested elements.
Finally, append it to the document with one statement, not many statements.
In my informal testing over the years, this will give you the best performance (some browsers may differ).
If HTML is ever declared in a variable, it should be simple and for a very specific purpose. Usually, this is not the right approach.
here's 2 possible cases :
Your HTML is static
Your HTML is dynamic
solution 1
In this case, wrap your HTML in double quotes, make it a string and save it in a variable. then push it inside HTML, here's a demo 👇
HTML
<div id="test"></div>
JavaScript
let selector = document.querySelector("#test");
let demo_1 = "<div id='child'> hello and welcome</div>"
selector.innerHTML = demo_1;
solution 2
In this case, wrap your HTML in back ticks, make it a template literal and save it in a variable. then push it inside HTML,
here, you can use variables to change your content. here's a demo 👇
HTML
<div id="test"></div>
JavaScript
let selector = document.querySelector("#test");
let changes = 'hello and welcome'
let demo_1 = `<div id='child'>${changes}</div>`
selector.innerHTML = demo_1;
You can concatenate raw HTML strings (being careful to escape text and prevent XSS holes), or you can rewrite jQuery (or something similar)
I have a situation where I pass text into a third party library, but if my model isPrivate, I'd like to add an element to the text.
return { id: item.id, text: (item.isPrivate == true) ? "<i class=\"icon-lock\" title=\"Private group.\"></i> " + item.label : item.label };
This creates issues with the way the third party library builds up its markup.
This is never a good idea, but third party libraries are there so that we don't have to write everything ourselves. In a situation like this, you have to rely on passing markup though javascript.
When i find a proper solution to this, I will give you an update