show all the values with .html [duplicate] - javascript

Lets say I have an empty div:
<div id='myDiv'></div>
Is this:
$('#myDiv').html("<div id='mySecondDiv'></div>");
The same as:
var mySecondDiv=$("<div id='mySecondDiv'></div>");
$('#myDiv').append(mySecondDiv);

Whenever you pass a string of HTML to any of jQuery's methods, this is what happens:
A temporary element is created, let's call it x. x's innerHTML is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes as a fresh DOM collection.
Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div> to jQuery(), jQuery will take a shortcut and simply do document.createElement('div').
EDIT: To see the sheer quantity of checks that jQuery performs, have a look here, here and here.
innerHTML is generally the faster approach, although don't let that govern what you do all the time. jQuery's approach isn't quite as simple as element.innerHTML = ... -- as I mentioned, there are a bunch of checks and optimisations occurring.
The correct technique depends heavily on the situation. If you want to create a large number of identical elements, then the last thing you want to do is create a massive loop, creating a new jQuery object on every iteration. E.g. the quickest way to create 100 divs with jQuery:
jQuery(Array(101).join('<div></div>'));
There are also issues of readability and maintenance to take into account.
This:
$('<div id="' + someID + '" class="foobar">' + content + '</div>');
... is a lot harder to maintain than this:
$('<div/>', {
id: someID,
className: 'foobar',
html: content
});

They are not the same. The first one replaces the HTML without creating another jQuery object first. The second creates an additional jQuery wrapper for the second div, then appends it to the first.
One jQuery Wrapper (per example):
$("#myDiv").html('<div id="mySecondDiv"></div>');
$("#myDiv").append('<div id="mySecondDiv"></div>');
Two jQuery Wrappers (per example):
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').html(mySecondDiv);
var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').append(mySecondDiv);
You have a few different use cases going on. If you want to replace the content, .html is a great call since its the equivalent of innerHTML = "...". However, if you just want to append content, the extra $() wrapper set is unneeded.
Only use two wrappers if you need to manipulate the added div later on. Even in that case, you still might only need to use one:
var mySecondDiv = $("<div id='mySecondDiv'></div>").appendTo("#myDiv");
// other code here
mySecondDiv.hide();

if by .add you mean .append, then the result is the same if #myDiv is empty.
is the performance the same? dont know.
.html(x) ends up doing the same thing as .empty().append(x)

Well, .html() uses .innerHTML which is faster than DOM creation.

.html() will replace everything.
.append() will just append at the end.

You can get the second method to achieve the same effect by:
var mySecondDiv = $('<div></div>');
$(mySecondDiv).find('div').attr('id', 'mySecondDiv');
$('#myDiv').append(mySecondDiv);
Luca mentioned that html() just inserts hte HTML which results in faster performance.
In some occassions though, you would opt for the second option, consider:
// Clumsy string concat, error prone
$('#myDiv').html("<div style='width:'" + myWidth + "'px'>Lorem ipsum</div>");
// Isn't this a lot cleaner? (though longer)
var newDiv = $('<div></div>');
$(newDiv).find('div').css('width', myWidth);
$('#myDiv').append(newDiv);

Other than the given answers, in the case that you have something like this:
<div id="test">
<input type="file" name="file0" onchange="changed()">
</div>
<script type="text/javascript">
var isAllowed = true;
function changed()
{
if (isAllowed)
{
var tmpHTML = $('#test').html();
tmpHTML += "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').html(tmpHTML);
isAllowed = false;
}
}
</script>
meaning that you want to automatically add one more file upload if any files were uploaded, the mentioned code will not work, because after the file is uploaded, the first file-upload element will be recreated and therefore the uploaded file will be wiped from it. You should use .append() instead:
function changed()
{
if (isAllowed)
{
var tmpHTML = "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').append(tmpHTML);
isAllowed = false;
}
}

This has happened to me . Jquery version : 3.3.
If you are looping through a list of objects, and want to add each object as a child of some parent dom element, then .html and .append will behave very different. .html will end up adding only the last object to the parent element, whereas .append will add all the list objects as children of the parent element.

Related

Get elements from source code stored in variable

I have this piece of code:
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
I need to get the text from an element which is in that source code. For example, consider the page having an element like:
<a class="something">something goes here</a>
I need to get that text of class 'something' with JavaScript. The request.source returns the source code with structure as it is.
You should be able to turn the source code into jQuery object and use it like usual from there.
var requestedSource = request.source;
$(requestedSource).find('a.something').first().text();
This works for me in a very simple test on jsfiddle.
Note that you may have to play around with whatever $.find() returns if you have more than one anchor element with the class "something" (I just used $.first() to simplify my example). In that case, you can iterate through the results of $.find() like an array.
If that solution doesn't work, another (but worse) way you could do it would be to write the requested code to a hidden div, and then run $.find() from the div (though if the first solution doesn't work, there is likely something going wrong with request.source itself, so check its contents).
For example:
$('body').append('<div id="requestedSource" style="display: none;"></div>');
And then:
$("#requestedSource").append(request.source);
$("#requestedSource").find("a.something").first().text();
If you're repeating this request often, you can also empty the hidden div by calling $.empty() on it when you're done processing:
$("#requestedSource").empty();
For best performance, you would want to store everything in a variable and write once:
var hiddenRequestSource = '<div id="requestedSource" style="display: none;">';
hiddenRequestSource += request.source;
hiddenRequestSource += '</div>';
$('body').append(hiddenRequestSource);
var myResults = $("#requestedSource").find("a.something").first().text();
$("#requestedSource").empty();

Extract div data from HTML raw DIV text via JS

I'm trying to extract data from a JS function that only renders an element's HTML - and I need the element's ID or class.
Example:
JS Element Value:
x = '<div class="active introjs-showElement introjs-relativePosition" id="myId">Toate (75)</div>';
I need to do get the element's id or class (in this case the id would be myId).
Is there any way to do this? Strip the tags or extract the text via strstr?
Thank you
The easiest thing to do would be to grab the jQuery object of the string you have:
$(x);
Now you have access to all the jQuery extensions on it to allow you to get/set what you need:
$(x).attr('id'); // == 'myId'
NOTE: This is obviously based on the assumption you have jQuery to use. If you don't, then the second part of my answer is - get jQuery, it's designed to make operations like these very easy and tackle compatibility issues where it can too
You may want to take a look at this:
var div = document.createElement('div');
div.innerHTML = '<div class="active introjs-showElement introjs-relativePosition" id="myId">Toate (75)</div>';
console.log(div.firstChild.className);
console.log(div.firstChild.id);

jquery access to element after append by variable as id

Via ajax i retrieve some json data, make it as html and append it to my page.
Here I have a problem. I cant access element by id, if id is variable.
For example, http://jsfiddle.net/f8g5e/1/
<div id="123">Hello</div>
<div id="321">Bye</div>
<div id="out"></div>
$(function(){
key = '123';
$('#' + key).hide();
$('#321').hide();
});
The simples thing is works! #123 and #321 elements are hidden. Yeah, it's pretty obviosly.
But, in my project, when I append data to page:
$('#123') //returns element
$('#' + key) //returns null
Some code:
// generating data
var htmlData = '<div id="123">Greetings!</div><div id="321">Bye bye</div>';
// appending data
$('#tweets').empty();
$('#tweets').append(htmlData);
What are the possible causes i can't access elements?
Thanks.
UPDATE
Dont know how it works in JSFiddle, but when I changed my IDs to properly names it began to work now. Thanks to all! Next time, I'll take more attention to w3c dom standarts ;) Happy New Year!
The only reason I can think of that $('#'+key) wouldn't work is because the variable key is undefined.
Note: you're not supposed to start an ID with a number according to the W3C spec. However, most browsers allow it, so I doubt this is causing your problem.
However, if you have two divs with the same ID attribute, then JavaScript will only select the first one it finds -- IDs are supposed to be unique. If this is happening, use classes instead.
You can either do this:
$(function() {
$('#321,#123').hide();
});
or you can do this:
$(function() {
var key = '123';
var doit = '321';
$('#' + key + ',#' + doit).hide();
});

.html() and .append() without jQuery

Can anyone tell me how can I use these two functions without using jQuery?
I am using a pre coded application that I cannot use jQuery in, and I need to take HTML from one div, and move it to another using JS.
You can replace
var content = $("#id").html();
with
var content = document.getElementById("id").innerHTML;
and
$("#id").append(element);
with
document.getElementById("id").appendChild(element);
.html(new_html) can be replaced by .innerHTML=new_html
.html() can be replaced by .innerHTML
.append() method has 3 modes:
Appending a jQuery element, which is irrelevant here.
Appending/Moving a dom element.
.append(elem) can be replaced by .appendChild(elem)
Appending an HTML code.
.append(new_html) can be replaced by .innerHTML+=new_html
Examples
var new_html = '<span class="caps">Moshi</span>';
var new_elem = document.createElement('div');
// .html(new_html)
new_elem.innerHTML = new_html;
// .append(html)
new_elem.innerHTML += ' ' + new_html;
// .append(element)
document.querySelector('body').appendChild(new_elem);
Notes
You cannot append <script> tags using innerHTML. You'll have to use appendChild.
If your page is strict xhtml, appending a non strict xhtml will trigger a script error that will break the code. In that case you would want to wrap it with try.
jQuery offers several other, less straightforward shortcuts such as prependTo/appendTo after/before and more.
To copy HTML from one div to another, just use the DOM.
function copyHtml(source, destination) {
var clone = source.ownerDocument === destination.ownerDocument
? source.cloneNode(true)
: destination.ownerDocument.importNode(source, true);
while (clone.firstChild) {
destination.appendChild(clone.firstChild);
}
}
For most apps, inSameDocument is always going to be true, so you can probably elide all the parts that function when it is false. If your app has multiple frames in the same domain interacting via JavaScript, you might want to keep it in.
If you want to replace HTML, you can do it by emptying the target and then copying into it:
function replaceHtml(source, destination) {
while (destination.firstChild) {
destination.removeChild(destination.firstChild);
}
copyHtml(source, destination);
}
Few years late to the party but anyway, here's a solution:
document.getElementById('your-element').innerHTML += "your appended text";
This works just fine for appending html to a dom element.
.html() and .append() are jQuery functions, so without using jQuery you'll probably want to look at document.getElementById("yourDiv").innerHTML
Javascript InnerHTML
Code:
<div id="from">sample text</div>
<div id="to"></div>
<script type="text/javascript">
var fromContent = document.getElementById("from").innerHTML;
document.getElementById("to").innerHTML = fromContent;
</script>

What's the best way to get this data to persist within Javascript event handlers using jQuery

My code is meant to replace radio buttons with dynamic ones, and allow clicking both the label and new dynamic radio element to toggle the state of the hidden with CSS radio box.
I need to send to questions.checkAnswer() three parameters, and these are defined within these initiation loops. However I always get last the last values once the loop has finished iterating. In the past I've created dummy elements and other things that didn't feel right to store 'temporary' valuables to act as an informational hook for Javascript.
Here is what I have so far
init: function() {
// set up handlers
moduleIndex = $('input[name=module]').val();
$('#questions-form ul').each(function() {
questionIndex = $('fieldset').index($(this).parents('fieldset'));
$('li', this).each(function() {
answerIndex = $('li', $(this).parent()).index(this);
prettyRadio = $('<span class="pretty-radio">' + (answerIndex + 1) + '</span>');
radio = $('input[type=radio]', this);
radio.after(prettyRadio);
$(radio).bind('change', function() {
$('.pretty-radio', $(this).parent().parent()).removeClass('selected');
$(this).next('.pretty-radio').addClass('selected');
questions.checkAnswer(moduleIndex, questionIndex, answerIndex);
});
prettyRadio.bind('click', function() {
$('.pretty-radio', $(this).parent().parent()).removeClass('selected');
$(this).addClass('selected').prev('input').attr({checked: true});
});
$('label', this).bind('click', function() {
$(radio).trigger('change');
questions.checkAnswer(moduleIndex, questionIndex, answerIndex);
$(this).prev('input').attr({checked: true});
});
});
});
Is it bad to add a pretend attribute with Javascript, example, <li module="1" question="0" answer="6">
Should I store information in the rel attribute and concatenate it with an hyphen for example, and explode it when I need it?
How have you solved this problem?
I am open to any ideas to make my Javascript code better.
Thank you all for your time.
It's not the end of the world to add a custom attribute. In fact, in many cases, it's the least bad approach. However, if I had to do this, I would prefix the attribute the with "data-" just so that it is compliant with HTML5 specs for custom attributes for forward compatibility. This way, you won't have to worry about upgrading when you want to get HTML5 compliant.
you need to say 'var questionIndex' etc, else your 'variables' are properties of the window and have global scope...
regarding custom attributes, i have certainly done that in the past tho i try to avoid it if i can. some CMS and theming systems occasionally get unhappy if you do this with interactive elements like textareas and input tags and might just strip them out.
finally $(a,b) is the same as $(b).find(a) .. some people prefer the second form because it is more explicit in what you are doing.
If the assignment of the custom attributes is entirely client-side, you must resolve this with jQuery data, something like this:
$("#yourLiID").data({ module:1, question:0, answer:6 });
for the full documentation see here

Categories

Resources