document.getElementById("print").innerHTML = good;
I want to start writing on new line when using this function for the second time
Here is what I would recommend:
Define the element once at the beginning to save getting it every time.
Create a custom function called print() which you can call more easily.
Use += to add and not overwrite content.
Use br elements to add line breaks after each printed message.
printDiv = document.getElementById("print");
function print(text) {
printDiv.innerHTML += text + '<br>';
}
print('This text');
print('is just here');
print('to test the function');
<div id="print"></div>
You are generating HTML.
A new line in HTML is usually created with a <br> element.
That might not be the right option for the data you are generating though. HTML is a semantic markup language so you should generate the markup that describes the semantics of the data you are working with.
That might involve creating a list with list items in it, multiple paragraphs, or something else.
Related
I've been following this tutorial: http://mariechatfield.com/tutorials/firebase/step5.html
But I wanted to spice it up and instead of printing the last database object, I want to print all of them.
I've tried printing off the database, which works fine. I just need to edit the Html. I tried using a line break, but nothing either. It keeps appending to the starting string instead of making a new line/container.
recommendations.limitToLast(10).on('child_added', function(childSnapshot) {
// Get the recommendation data from the most recent snapshot of data
// added to the recommendations list in Firebase
recommendation = childSnapshot.val();
console.log(recommendation);
// Update the HTML to display the recommendation text
$("#title").append(recommendation.title)
$("#presenter").append(recommendation.presenter)
$("#link").append(recommendation.link)
var x = '\n';
x;
// Make the link actually work and direct to the URL provided
$("#link").attr("href", recommendation.link)
});
I hope to be able to have an individual container for each database element.
Per request, posting comment as answer:
Great job! The only change you have to make is to change \n to <br>. HTML removes whitespace (like your newline). So to replicate that line break you have to use the HTML BR element. Then you'll need to append that to your existing HTML of-course.
I am creating a helper function that is called by a templating library. My helper generates at the moment a div with a guid id - which is used as a placeholder - as well as a script which calls back to the server every second to get content to put into that placeholder - with essentially this code:
$.get( url + guid).done( result => $("#" +guid).html( result));
so - it all works perfectly - unless my helper function is used inside a table block - in which case, because <div> is not an allowed child of tbody - chrome kicks it out... so when I actually turn up with rows and columns later - they are no longer inside the table block - they turn up above it.
Now, of course the problem is that you get no context in the template renderer - ie it's completely impossible for me to know whether or not I'm in a table.
Can anyone think of any way I can put any sort of placeholder - text, comment, whatever inside my initial rendered html in a way that I can update it multiple times and the new html I insert will always appear exactly in the same place and context the original template instruction was?
You could use the <span></span> element.
Here's a pretty straightforward explanation:
The tag is used to group inline-elements in a document.
The tag provides no visual change by itself.
The tag provides a way to add a hook to a part of a text or a
part of a document.
I found an answer - I'd still like a better one, but if I use comments like <!-- start --> and <!-- stop --> I can replace them with this:
var inner = document.body.innerHTML;
var comment = s => "<!-- " + s + " -->";
var reg = new RegExp( comment("start") + "(.|\n)*" + comment("stop"), "gim");
var replaced = inner.replace( reg, comment("start") + "<tr><td>1</td><td>2</td></tr>"
+ comment("stop"));
document.body.innerHTML = replaced;
being careful to construct the regexp so that it doesn't match itself :) Anyway - not ideal replacing the entire innerhtml - but it's my answer unless anyone can come up with something better. Because comments don't get moved - from anywhere.
I'm trying to create a function in javascript (or jQuery) that will take a variable filled with html and output a plain text version. The function needs to strip the html tags and insert line breaks at the end of heading and paragraph tags.
I've been going round in circles for ages with this. There are lots of examples of how to take a DOM object, e.g. document.body.innerHTML and remove the tags. However, I'm using a variable filled with html and the results are not the same.
This is the supposed duplicate solution: http://jsfiddle.net/8JSZX/. However, create an html variable and use that and you get: http://jsfiddle.net/JjXXY/ - which does not preserve the line breaks.
The html variable would be something like:
var html = '<h1>This is a heading</h1><p>This is a paragraph</p><p>This is another paragraph</p>'
If there is a better solution to this I'm open to suggestions!
Gave it a shot:
var html_string = '<h1>Test</h1><p>A paragraph with a link</p>';
var regex = /<(\/?)[a-zA-Z0-9][^>]*>/g;
var stripped = html_string.replace(regex, '');
$("#result").html(stripped);
See: http://jsfiddle.net/Y6q2j/5/
Is there any way to to do something similar to ruby gsub in javascript? I have a local html file that I want to process and replace certain template variables with content but I cannot figure out how to substitute out the template variables with the new content. The html contains fragments like below:
<div id="content">
<h1>{{title}}</h1>
{{content}}
</div>
Now if I wrap every template variables in a named div then I can use something like jquery's replaceAll method to replace the template variable with its content but I cant figure out how to do it without wrapping every variable in a div.
I just want to do something like $('document').gsub("{{title}}", "I am a title").
Anyone have any ideas?
Thanks for your help!
If others were looking for an equivalent to gsub in general, this only replaces the first match:
"aa".replace("a", "b") // "ba"
//g replaces all matches:
"aa".replace(/a/g, "b") // "bb"
"aa".replace(new RegExp("a", "g"), "b"); // "bb"
You can access the raw HTML via a DOM element's innerHTML property, or using JQuery's html property wrapping it, and then perform the substitution:
var html = $(document).html();
$(document).html(html.replace('{{title}}', 'I am a title');
EDIT:
As pointed out by Antti Haapala, replacing the entire document HTML can have side-effects you don't want to deal with, like scripts being reloaded. Thus, you should drill down to the most specific DOM element possible before performing the substitution, i.e.:
var element = $('#content');
var html = element.html();
element.html(html.replace('{{title}}', 'I am a title');
Well, you can use String.replace with a regex, but really, what you could use are jQuery Templates.
http://api.jquery.com/category/plugins/templates/
I recently used Handlebars to take a data attribute (template) from a table and inject another value (record id) from one of its rows:
// data-row-url="http://example.com/people/{{id}}"
var table = $(this).closest('.data_grid table');
if(table.attr('data-row-url')) {
var record_id = $(this).data('record-id')
var show_url_template = table.data('row-url');
var url_template = Handlebars.compile(show_url_template)
var url = url_template({ id: record_id });
$.getScript(url);
}
For context this code runs from inside an onclick event for the table's tr elements and fetches the clicked record via ajax.
I believe that might be a mustache template. You might want to check mustache.js. I think you might be able to compile that to JS.
I have, for example, markup like this
<div id="content">
<p>Here is some wonderful text, and here is a link. All links should have a `href` attribute.</p>
</div>
Now I want to be able to perform some regex replace on the text inside the p element, but not in any HTML, i.e. be able to match the href within backticks, but not inside the anchor element.
I thought about regex, but as the general consensus is, I shouldn't be using them to parse HTML.
My current method of doing this is like so: I've got a bunch of words in an array, and I am looping through them and making an object of data like so:
termsData[term] = {
regex: new RegExp('(\\b' + term + '\\b)', 'gmi'),
replaceWith: '<span>{TERM}</span>'
};
I then loop through it again, making the replacements like so:
var html = obj.html();
$.each(terms, function(i, term) {
// Replace each word in the HTML with the span
html = html.replace(termsData[term].regex, termsData[term].replaceWith.replace(/{TERM}/, '$1'));
});
obj.html(html);
Now I did a lot of this last night at an ungodly hour, and copying and pasting it into here seems to make think I should refactor some of this.
So from you should be able to tell, I want to be able to replace plain text, but not anything inside a HTML tag.
What would be the best way to do it?
Note: The source code is coming from here if you'd like a better look.
You're right to not want to be processing HTML with regex. It's also bad news to be assigning huge chunks of .html(); apart from the performance drawbacks of serialising and reparsing a large amount of HTML, you'll also lose unserialisable data like event listeners, form data and JS properties/references.
See the findText function in this answer and call something like (assuming obj is a jQuery wrapper over your topmost node to search in):
findText(obj[0], /\b(term1|term2|term3)\b/g, function(node, match) {
var span= document.createElement('span');
node.splitText(match.index+match[0].length);
span.appendChild(node.splitText(match.index));
node.parentNode.insertBefore(span, node.nextSibling);
});