Converting String to DOM - javascript

My Ajax functions gives me HTML-Elements as String back, and this String I want to append in my Document as DOM Element.
Something like
parentNode.appendChild(responseText);
What will be the best way to do this.

parentNode.innerHTML += responseText;

you can use innerText to do it

There can be more possible cases. You should clarify a bit.
If you get a string that should be an object and it's not existing yet, then you should use this: var tempObj = document.createElement("yourString"); then you can just use tempObj to handle it.
If you get a string that is the name or ID of an existing object, then use: var tempObj = document.getElementByName("yourString");
or
var tempObj = document.getElementById("yourString");

You can use the DOM methods this library provides, for example the insert() or update() method:
$('parentId').insert(yourString);
or
$('parentId').update(yourString);
http://api.prototypejs.org/dom/element/insert/
http://api.prototypejs.org/dom/element/update/
Note that innerHTML is not standarized yet, so using prototype, you can be sure those methods are cross browser compatible.
Good luck!

The simple way for converting String to DOM and vice versa is presented on this link:
http://famulatus.com/ks/programming/java/item/335-convert-xml-dom-to-string-and-string-to-xml-dom.html

Related

How can I convert a jQuery object to a JS array?

Here is my old code:
checkboxes = document.getElementsByName('foo');
As you know, checkboxes will be an array. Now I need to limit selecting scope. So this is my new code:
checkboxes = $('.myclass input[name=foo]');
But in this case checkboxes isn't an array anymore, it's a jQuery object. How can I make it the same as getElementsByName('foo')'s result?
Note that $('.myclass input[name=foo]')[0] won't work either.
Try .toArray()
checkboxes = $('.myclass input[name=foo]').toArray();
Use this
var checked = [];
$.each($("input[name='foo']:checked"), function(){
checked.push($(this). val());
});
Charlie already pointed out that jQuery objects have a toArray() function. That would work I think. Figured it was also worth noting that there is also a .makeArray() function for generally converting array-like objects to native JavaScript arrays. https://api.jquery.com/jQuery.makeArray/
You can use .map() and create an array of underlying DOM which getElementsByName() returns
checkboxes = $('.myclass input[name=foo]').map(function(){ return this;}).get();
I would recommend #Charlie answer
You don't need to convert to Node elements array. Change your function to
function toggle(source, target) {
$(target).find('input[name=foo]').prop('checked', source.checked);
}
Usage
toggle(source, '.compare_people')
toggle(source, '.compare_posts')
document.querySelectorAll("input[name=foo]")
Getting javascript object from jquery object by $('selector')[0] should work. See the answer from this link How to get javascript control from JQuery object?
I suspect your selector is the reason why the above approach doesn't work. Add double quotes to name value will make it work:
checkboxes = $('.myclass input[name="foo"]');

How can I use a Javascript variable as a DOM

This is kinda hard to word so i'm hoping you understand it:
I have an entire page in a variable. I need to be able to do getElementsByClassName on it. But how?
I've tried:
$.get( base_url, function( data ) {
var something = data.getElementsByClassName('.user_name');
});
If your URL returns HTML, data is a string. Since you're using jQuery, you can have jQuery parse it for you:
var dom = $(data);
Then you can use all the usual jQuery methods on that disconnected set of elements, so:
var userNames = dom.find(".user_name");
If you weren't using jQuery, you could have the browser parse that into elements for you:
var div = document.createElement('div');
div.innerHTML = data;
...and then use use DOM methods on that disconnected div. I wouldn't use getElementsByClassName, though; querySelectorAll has better support; basically, it's in all modern browsers and also in IE8, but IE8 doesn't have getElementsByClassName.
var userNames = div.querySelectorAll(".user_name");
You are mixing pure javascript with JQuery
Try this
data.getElementsByClassName('user_name');
instead of
data.getElementsByClassName('.user_name');

Are jQuery objects actual DOM objects? Is it correct to add properties to them?

Through this question I found out here that there are downsides in extending DOM objects.
Is it OK to do something like the following?
var tr = $('<tr>');
tr.myCustomProperty = 'Some string value';
I know that there is a .data() method on jQuery, but the above seems easier to work with. I also wonder if my tr variable is holding an actual tr DOM Element or any other kind of object.
Kevin is incorrect. You can store something in the TR in most browsers by doing the following:
var tr = $('tr').eq(0); // get a single TR from the DOM
var actualElement = tr[0]; // get the actual element object from the jQuery object
actualElement.myCustomProperty = 'Some string value';
jQuery handles DOM objects in special array called jQuery object. You can think of it as array of DOM elements which is extended to have all the jQuery methods.
You can access the DOM element in your example like this:
tr[0]
but all the reasons not to store data that way still apply.
As #Kevin B mentioned, it's not ok to do what you're trying to do (extending jQuery object) because you'll lose the custom properties on every reinitialization.

Return jQuery object (instead of DOM) from jQuery array using index

I have a jQuery array of <span>s and I'd like to get just one of them as a jQuery object so that I can string additional methods on it. Something like $mySpans[2] (which returns a string), or $mySpans.get(2), (which returns the DOM element directly).
I know that this will work:
$($mySpans[2]).someJQueryMethod( ... );
...but it seems a little redundant. What is the right way to do this?
Like this:
$myspans.eq(2).method();
jsFiddle Demo
You are going to want to use eq. Note that it will return the jQuery object wrapped element at that index, so if you only have one match you should use 0 (which follows that 2 will return the third of the set).
var $thirdMatch = $mySpans.eq(2);//== jQuery object with third match
var htmlElement = $thirdMatch[0];//== actual dom element
var matchedHtml = $thirdMatch.html();// call some jQuery API method
It is common practice when storing jQuery objects to use a $variableName for readability purposes.

Overriding native function?

The native document.createElement() is silly-stupid (it takes only a tag name and no attributes). How come I can't override it? How come this doesn't work?
var originalFunction = document.createElement;
document.createElement = function(tag, attributes) {
var element = originalFunction(tag);
if (attributes) {
for (var attribute in attributes) {
element.setAttribute(attribute, attributes[attribute]);
}
}
return element;
};
The problem is that browsers blow up when you try to replace a native function. Since document is not a JavaScript primitive, you can't create a prototype for it either. WTF.
As far as I can tell the problem is that a call to the document.createElement() function even when referenced has to be from the document. So modify your code:
var element = originalFunction.call(document, tag);
FWIW (informational): you can override "native" methods, in some cases, and in some browsers at least. Firefox lets me do this:
document.createElement = function(f) { alert(f); };
Which then does as you expect when invoked. But your whole block of code above throws an error, at least via Firebug.
Philosophically, you should be able to do this. You can certainly, say, redefine methods on the Array object, etc. But the window (DOM) methods are not covered by ECMAScript, and so they're probably allowed to be implementation-dependent. And of course, they are this way for security reasons.
Why not just use the method in your own function- write it the way you want, and never write document.createElement again....
document.create= function(tag, parent, attributes){
tag= document.createElement(tag);
for(var p in attributes){
if(p== 'css') tag.style.cssText= attributes.css;
else if(p== 'text') tag.appendChild(document.createTextNode(attributes.text));
else tag[p]= attributes[p];
}
if(parent) parent.appendChild(tag);
return tag;
}
document.create('p',document.body,{css:'font-style:italic',className:'important',title:'title',
text:'whatever text you like'});
As far as I know you cannot override native methods for security reasons. For non-native methods it's no problem at all.
There's no way to override that, however you can do some hack around if you not affraid of passing non conventional parameter(s) to a native function. So the thing about createElement that its ment to be the part of the XML DOM, thus you can create whatever tagname you want. And here is the trick, if you pass your attributes as a part of the first parameter (the tagname), separating them with the delimiters of your choise, and then listening to the onchange event of the DOM and if your delimiters are presented in any tag, replace them with the proper markup, using RegExp for example.
The proxy pattern mentioned at JavaScript: Overriding alert() should work for this.
It's mentioned in jquery docs but doesn't look like it actually has a dependency on jQuery.
More info here: http://docs.jquery.com/Types#Proxy%5FPattern
Try this.
document.constructor.prototype.createElement = _ => `P for "pwned"`;
console.log(document.createElement("P"));

Categories