This question is not related to coding issues but how we write our codes. For example take the append function. When we use jQuery append to insert long divs, it is easy to lose track of it's correctness. Example:
$('#someDiv').append('<div><span><div> .............. hundreds of div here ..... </div></span></div>');
Is it possible to convert this to a readable format, for example using multi-lines. I tried
$('#someDiv').append('<div>'+
+'<span>'+
+'<div> ...... and you get the point')
This doesn't seem to work. This question may be easy for some but it is not so obvious for me. Also although I minify js files at the end, it would be nice not to lose track of the elements while writing the code.
If you have to add the HTML inline style I would suggest the following format.
var html =
'<div class="somediv">\
<div class="otherdiv">\
.
..
...
</div>\
</div>';
$('#somediv').append(html);
You can do it this way -
$('#someDiv').append($('<div>').append($('<span>'))
.append($('<div>'))
.append($('<div>'))
.append($('<div>'))
.append($('<div>'))
)
You can also add css styles, add class, change html while appending these html elements (wrapped in jQuery object)
$('<div>').css('color','red')
$('<div>').addClass('someClass')
$('<div>').html("and you get the point")
My solution would be to create all these elements
div1 = $(document.createElement('div'));
div1.attr(..);
div1.css(..);
container.append(..)
This means a lot of code but you can outsource it, can easily change attributes and its good readable...
Related
I have for example such piece of html:
var html = '<p>Title</p><b>edit me</b><i>remove me</i>';
I want to change title in it, but do not want to use regexp or string replace
functions for this, because if title would match tag name, then html could be corrupted.
I now trying to adopt jQuery for this, because it seems capable, but in reality things not so easy. Here is code:
$( $(html)[0] ).text('New title');
console.log(html); // --> prints out original html with old title
Any idea how to make this code work if it is at all possible ?
html = $('<div/>').html(html).find('p').text('New title').end().html();
http://jsfiddle.net/bEUHN/
Note: There are 3 wrapper elements in the created jQuery object using $(html), for selecting the p element you should use filter method.
$(html).filter('p').text('New title');
Example code
var jqxhr=$.getJSON("http://search.twitter.com/search.json?callback=?",{q:query},
function(data) {
... question.
});
Question
Now i need to create for each tweet result something like this (for example...)
<article class="tweet">
<header>
<img class ="tweet_img"src="data.profile_image_url"/>
</header>
<p class="tweet-text">data.text</p>
</article>
Well, i know several ways to append each result to the document:
Creating a big HTML string and add the data from JSONP and append this to some container.
Create a p element, a header element... work with them and after that append a final Element to some container.
Now the question is: with your experience what is the correct way to do this?
I mean the correct way using good principles.
Please dont ask about the html, it's dumb example.
Thanks.
Well, best practices will tell you not to use the innerHTML property of a DOM element, which is what you'd be doing with option 1. But unless you are concerned about immediately operating on the code with Javascript, attaching events, or security concerns around tag injection (I don't know how much this is an issue anymore) then creating an HTML string and inserting it using innerHTML is going to be a lot quicker and easier to update.
There are several valid approaches that each have their own advantages...
The technique of just generating the HTML as a string in your java code and adding it with .innerHTML is known to be one of the fastest performing approaches...but it provides very little validation of your HTML.
Alternatively, you can build the HTML using DOM methods directly, creating tags and appending them to build the structure. This is generally safer in that you have more validation going on, but the DOM methods are extremely wordy, which makes them a bit painful to type...and the code is even more verbose as you have to add attributes one at a time as well.
My personal preference, especially since you're already using JQuery, would be to build the tags and text nodes using JQuery, and put them together using JQuery, which allows you to do so in bite-sized, more human-verifiable units, without becoming overly verbose.
This also has the advantage that JQuery's methods of producing new tags give you additional support for older browsers that did not adhere to DOM standards. Hopefully you don't actually have to care whether your page works for those older browsers, but more compatibility never hurts either.
In that approach, you'd write something like the following:
var article = $('<article class="tweet"></article>');
var header = $('<header></header>');
var image = $('<img class="tweet_img" src="' + data.profile_image_url + '"></img>');
var tweet = $('<p class="tweet-text">' + data.text + '</p>');
header.append(image);
article.append(header, tweet);
$("#id_of_content_area_to_add_the_tweet_to").append(article);
The cleanest way I know how is to use a template system like Mustache, instead of "HTML in JS"
var template = html_string, //HTML from a string or from AJAX
data = {...data...}, //structured data
html = $(Mustache.render(template,data)); //wrap in jQuery to operate
html.appendTo(somewhere_in_DOM);
If you want to attach some event handlers to the elements then you should generate them separately.
But if you don't want to attach any event handler then i will recommend first method
$("body").append('<article class="tweet"><header><img class ="tweet_img" src="'+data.profile_image_url+'"/></header><p class="tweet-text">'+data.text+'</p></article>')
I will recommend you to use some Template engine like Handlebars.js Which is the right solution for your problem.
Which is having many more options which has many more conditional options which can be useful in feature. Just visit the above link you will have some idea.
I'm writing an application with some client-side JS that I use to update the DOM reasonably often.
The thing is that doing something like:
$('#id').html('<div class="' + class + '">' + content + '</div>');
multiple times and leaving HTML lying randomly round your JavaScript isn't very pretty and difficult to maintain.
Is there a JavaScript equivalent (or alternate solution) to the way Lithium handles this in it's view helpers.
See:
http://li3.me/docs/lithium/template/Helper::_render()
http://li3.me/docs/lithium/util/String::insert()
For examples.
Basically in the PHP version you would make an associate array of common strings and a simple method to replace to replace certain marked parts of those strings with variables of the same name.
Another silly example (psuedo-code:)
var strings = {
'div': '<div {:attr}>{:content}</div>'
};
console.log(render('div', {id: 'newElem'}, 'Hello, World!'));
// Output: <div id="newElem">Hello, World!</div>
If you have any better suggestions on how you handle storing HTML in your JavaScript and keep it from going all over the place then I'd very much like to hear it.
Yes, use jQuery templates or Underscore templates (my favorite) or any other JS templating engine out there.
Also, check this question for a discussion on performance of templating engines: Improve jQuery template performance
If you don't want to use a templating system, and have many html snippets that must be created many times, then you can use another technique :
Create a div in your main html file, give it a specific css class or id
Using css, make this div invisible
Inside is div, create the "template" divs, each one will contain a "snippet", each one with proper class or id
Using js (jquery, whatever) when you need it, clone the "template" div, append it where you need it, and then customize it.
Using jquery this is very easy, and your template "divs" are asy accessible to any html designer.
I'm on a mobile device now, and posting code snippets is a bit difficult, but let me know if want some examples.
jQuery encourages you to dynamically construct your DOM nodes instead of doing string concatenation:
$("#id").html(
$("<div />").addClass(class).text(content))
In general, you can use the jQuery attribute methods to construct such nodes, and many of these methods take mappings as you say you like. For example:
$("#id").append(
$("<div />")
.attr({id: "newElem"})
.css({width: "100%", color: "red"}))
I've got a little bit of javascript embedded in my html (using a .aspx file). I want to perform some sort of if statement which then determines whether or not some sort of chart is displayed. This chart is displayed using html, and I'm assuming the if statement should be written in javascript. However, I don't really know how to "run" this html code from within java. It is basically just drawing a table. Any suggestions? I've seen document.write, but I've only seen that being used with single lines.
You don't really "run" an HTML code. HTML is a markup language and it is mostly used to format and arrange elements that are displayed in the web browser.
The problem you are probably trying to solve is: Display or hide an element based on some condition. A JavaScript code like this is what you want.
if (condition) {
document.getElementById('chart').style.display = "none"
} else {
document.getElementById('chart').style.display = ""
}
Of course whatever element is responsible for displaying the chart should have an id="chart" attribute. e.g. <div id="chart"><!-- Chart related code goes here --></div>.
The JavaScript code I have given alters the display CSS property of this element to hide it or make it visible.
In case this is not what you want but you want to dynamically modify the HTML responsible for the chart, then you need to use the innerHTML property of the element.
Example:
if (condition) {
document.getElementById('chart').innerHTML = "<!-- HTML Code for the chart here -->"
} else {
document.getElementById('chart').innerHTML = ""
}
I'm assuming the if statement should be written in javascript
Unless you are testing something that you can only find out out in JS, then do it server side in your ASP.NET code.
I don't really know how to "run" this html code from within
This is covered by chapter 47 of Opera's WSC: Creating and modifying HTML. You may wish to read some of the earlier chapters first.
java
Java has about as much in common with JavaScript as Car does with Carpet. They are completely different programming languages.
Try writing the if statement in javascript and then rendering the html with the JQuery html() function. Just use a custom html id to locate where you want the html code to go.
<div id = "custom-tag"> </div>
<script>
if (true){
$('#custom-tag').html('YourHtmlString');
} else {
$('#custom-tag').html('DifferentHtmlString');
}
</script>
Read more about html() here: http://api.jquery.com/html/
YourHtmlString & DifferentHtmlString is where you should store your custom html in string format. It will then be rendered wherever you included "div id = 'custom-id'
Hope this helps!
How do I get the values in between a DIV tag?
Example
<div id="myOutput" class="wmd-output">
<pre><code><p>hello world!</p></code></pre>
</div>
my output values I should get is
<pre><code><p>hello world!</p></pre>
First, find the element. The fastest way is by ID. Next, use innerHTML to get the HTML content of the element.
document.getElementById('myOutput').innerHTML;
document.getElementById("myOutput").innerHTML
innerHtml is good for this case as guys suggested before me,
If you have more complex html structure and want to traverse/manipulate it I suggest to use js libraries like jQuery. To get want you want it would be:
$('#myOutput').html()
Looks nicer I think (but I wouldn't load whole js library just for such simple example of course)
Just putting all above with some additional details,
If you are not sure about that div having some id is not there on html page then to make it sure please use.
var objDiv = document.getElementbyId('myOutput');
if(objDiv){
objDiv.innerHTML;
}
This will avoid any JavaScript error on the page.