Suppose I have a template saved in HTML and using standard underscore syntax.
My understanding is that I can grab the template using jQuery as such:
var html = $('#item-foo').html()
From there I can interpolate it using
var interpolated = _.template(html, {prop: "and_values"});
To create a DOM element in the JavaScript I can use this utility function
// converts HTML string to DOM object
Pub.HTMLToElement = function (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.firstChild;
};
var element = HTMLToElement(interpolated);
and finally I have my element in JavaScript which all began with a template in the HTML.
Is this the best way to do this?
It seemed long so I just wanted to validate.
This is a little bit simpler and you are already using jQuery:
HTML:
<script id="template" type="text/template">
Hello <%=name%>, how are you?
</script>
<div id="container" />
JS:
var str=$('#template').html();
var interpolated = _.template(str, {name: "pizza"});
$('#container').append($('<div/>').html(interpolated));
JSFiddle: http://jsfiddle.net/QAT4n/
If you are using jQuery, jQuery automatically converts HTML to an element. This would be a shorter way:
var element = $(interpolated).get(0);
See http://api.jquery.com/get/ and http://api.jquery.com/jQuery/#jQuery2
So the whole process would be like this:
var html = $('#item-foo').html()
var interpolated = _.template(html, {prop: "and_values"});
var element = $(interpolated).get(0);
And could be cleaned up to this:
var interpolated = _.template(
$('#item-foo').html()
, {
prop: "and_values"
});
var element = $(interpolated).get(0);
Related
I have a string containing html code, something like this: http://jsbin.com/ocoteg/1.
I want to parse this string, make some changes (just for example: change all links to a span), and then get the modified html string back.
Here is a jsbin, where I started this, but I can't make it work: http://jsbin.com/okireb/1/edit.
I get the html string, I parse it with jquery, but I can't replace the links, and get the modified html string back.
UPDATE
Why the downvote? What is the problem with this question?
You can do it in a loop also
dom.each(function(i,v){
if(v.tagName == "A"){
dom[i] = $('<span/>').html($(v).html())[0]; // replace it right away with new span element
}
});
var newString = $('<div>').append(dom.clone()).html(); //<-- to get new string http://stackoverflow.com/a/652771/1385672
console.log(newString);
EDIT:
Here's how you can do it keeping the other tags
var dom = $(text.split('\n'));
$(dom).each(function(i,v){
var ele = $(v)[0];
if($(ele).is('a')){
dom[i] = $('<div>').append($('<span/>').html($(v).html())).html();
}
});
var newString = dom.get().join('\n');
http://jsbin.com/okireb/32/edit
Use find instead of filter :
var dom = $('<div>'+text+'</div>');
dom.find('a').each(function() {
var el = $(this);
var html = el.html();
var span = $('<span/>').html(html);
el.replaceWith(span);
});
console.log(dom.children());
Note that I wrap everything for the case where the initial dom isn't one element.
Demonstration
To get the html back as a string use
var html = dom.html();
This should be what you want (can be improved)
var text = '<!DOCTYPE html><html><head><meta charset=utf-8 /><title>JS Bin</title></head><body>Link 1Link 2Link 3</body></html>';
var body_content = text.substring(text.indexOf('<body>') + 6, text.indexOf('</body>'));
var $dom = $('<div/>').html(body_content);
$('a', $dom).each(function() {
$('<span>' + $(this).html() + '</span>').insertAfter($(this));
$(this).remove();
});
var text_new = text.replace(body_content, $dom.html());
// text_new contains the entire HTML document with the links changed into spans
You could do it with .replace.
Probably not the nicest way of doing it though.
dom = dom.replace(/<a /g,'<span');
dom = dom.replace(/<\/a>/g,'</span>');
Demo: http://jsbin.com/okireb/14/edit
Given the following code using Handlebars.js:
var templateString = "<div>{{{nameContainer}}}</div>";
var handlebarTemplate = handlebars.compile(templateString);
var context = {
nameContainer: '<div id="myID">my name is John Doe</div>'
}
var html = handlebarTemplate(context);
var body = document.getElementsByTagName('body') [0];
body.innerHTML = html;
What's the simplest way to add an event listener on #myID using Handlebars.js without the need to use something like document.getElementById('myID').addEventListener(...) after html is added to the DOM?
I have a JavaScript variable:
var s =
"<html><head><style>body{a:b;c:d}</style></head><body></body></html>";
First, I am extracting the content inside <style> tags:
s = s.split(/(<style[^>]*>|<\/style>)/i)[2];
// s == "body{a:b;c:d}";
Then I am doing something with s and after the manipulation I need to append it on <style> tags.
How can I insert s between <style> and </style> ?
Example: Modified var s = "body{x:h;f:l;}";
so I need the resulting content like this:
"<html><head><style>body{x:h;f:l;}</style></head><body></body></html>";
Update: jQuery is allowed - But only string manipulation is
allowed. Pure JavaScript solutions have first priority.
var s = "<html><head><style>body{a:b;c:d}</style></head><body></body></html>";
var b = s.split(/(<style[^>]*>|<\/style>)/i)[2];
s = s.replace(b,"body{x:h;f:l;}");
finally, s is what you want.
Does this work for you:
var s ="body{a:b;c:d}";
var newS = s.replace("body{a:b;c:d}", "body{x:h;f:l;}");
alert(s);
alert(newS);
Use below mentioned code
var someHTML = "<html><head><style>body{a:b;c:d}</style></head><body></body></html>";
var styleContents = someHTML.split(/(<style[^>]*>|<\/style>)/i)[2];
document.getElementById('style').innerHTML = styleContents;
Say I have this HTML code:
<img id="idgoeshere" src="srcgoeshere" otherproperty="value" />
I can reference the element by its id: $('#idgoeshere')) Now, I want to get all the properties and their values on that element:
src=srcgoeshere
otherproperty=value
Is there some way I can do that programmatically using jQuery and/or plain Javascript?
You can get a listing by inspecting the attributes property:
var attributes = document.getElementById('idgoeshere').attributes;
// OR
var attributes = $('#idgoeshere')[0].attributes;
alert(attributes[0].name);
alert(attributes[0].value);
$(attributes).each(function()
{
// Loop over each attribute
});
The syntax is
$('idgoeshere').attr('otherproperty')
For more information - http://api.jquery.com/attr/
Yes you can!
Jquery:
var src = $('#idgoeshere').attr('src');
var otherproperty = $('#idgoeshere').attr('otherproperty');
Javascript:
var src = document.getElementById('idgoeshere').getAttribute('src');
var otherproperty = document.getElementById('idgoeshere').getAttribute('otherproperty');
You can use attr for that:
For eg.
var mySrc = $('#idgoeshere').attr("src");
var otherProp = $('#idgoeshere').attr("otherproperty");
If you want to just get a list of all the attributes, see the answers to this question: Get all Attributes from a HTML element with Javascript/jQuery
Try this:
var element = $("#idgoeshere");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});
I have some HTML loaded in WebView like this:
<html><head></head><body>before <myTag>Content</myTag> after</body></html>
I want to replace element myTag with custom text so it should look like:
<html><head></head><body>before ____MY_CUSTOM_TEXT___ after</body></html>
Also I can't change initial HTML.
How I can do this with JavaScript?
My not finished code:
var elements = document.getElementsByTagName( 'myTag' );
var firstElement = elements[0];
var parentElement = firstElement.parentNode;
var html = parentElement.innerHTML;
parentElement.innerHTML = html.replace(?????, '____MY_CUSTOM_TEXT___');
I don't know how to get string value of element to replace (?????).
Here you go:
var txt = document.createTextNode('____MY_CUSTOM_TEXT___');
parentElement.replaceChild(txt, firstElement);