Get the outer HTML of a detached JQuery object [duplicate] - javascript

This question already has answers here:
Get selected element's outer HTML
(30 answers)
Closed 6 years ago.
I'm creating a html node by jQuery (the sample is of tag <input> but can be of any type):
var x = $("<input>");
Then I add its attributes through a series of .prop() function:
x.prop("id", ...).prop("class", ...);
Now a certain plugin does not support JQuery object, but rather the HTML string so I invoke the plugin through this:
var n = plugin.method1(x.html())
Which I though will work but .html() returns an empty string. Although some said it will be resolved if I append it first on the DOM tree. How can I get its HTML string without appending it first in the DOM tree?

You can use .prop() to get outerHTML property.
x.prop('outerHTML');
var x = $("<input>");
x.prop('id', 'yahooooooooo');
console.log(x.prop('outerHTML'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Bit simpler to index the HTMLElement behind it and access the outerHTML property like this:
x[0].outerHTML

Related

JS how to get twitter's name [duplicate]

This question already has answers here:
How to Get Element By Class in JavaScript?
(12 answers)
Closed 9 years ago.
Using JavaScript, we can get element by id using following syntax:
var x=document.getElementById("by_id");
I tried following to get element by class:
var y=document.getElementByClass("by_class");
But it resulted into error:
getElementByClass is not function
How can I get an element by its class?
The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.
The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:
var y = document.getElementsByClassName('foo');
var aNode = y[0];
If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:
var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);
As yckart suggested querySelector('.foo') and querySelectorAll('.foo') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:
querySelector(all)
getElementsByClassName
Don't use w3schools to learn something
Refer to MDN for accurate information
Another option is to use querySelector('.foo') or querySelectorAll('.foo') which have broader browser support than getElementsByClassName.
http://caniuse.com/#feat=queryselector
http://caniuse.com/#feat=getelementsbyclassname
You need to use the document.getElementsByClassName('class_name');
and dont forget that the returned value is an array of elements so if you want the first one use:
document.getElementsByClassName('class_name')[0]
UPDATE
Now you can use:
document.querySelector(".class_name") to get the first element with the class_name CSS class (null will be returned if non of the elements on the page has this class name)
or document.querySelectorAll(".class_name") to get a NodeList of elements with the class_name css class (empty NodeList will be returned if non of. the elements on the the page has this class name).
you can use
getElementsByClassName
suppose you have some elements and applied a class name 'test', so, you can get elements like as following
var tests = document.getElementsByClassName('test');
its returns an instance NodeList, or its superset: HTMLCollection (FF).
Read more

How can I copy a whole html element? [duplicate]

This question already has answers here:
full HTML of object returned by jQuery selector
(10 answers)
Closed 8 years ago.
Let's say I have some elements like:
<div id="some-id" class="some-class">
<h1>Something here</h1>
</div>
And I would like to copy the whole some-id element together with all it's children, send it to database and then, when reloading the page, append them to the body.
I tried:
clone() and I got: "prevObject: jQuery.fn.jQuery.init[0], context: undefined, constructor: function, init: function, selector: ""…"
cloning and JSON.stringify() and I got one warning and one error in the console:
'Attr.ownerElement' is deprecated and has been removed from DOM4 (http://w3.org/tr/dom).
Uncaught TypeError: Converting circular structure to JSON
What can I use to end up with the html structure of my element that I can put in the database and re-use it?
If you want to persist a html structure, then you need to use its html string, you can't stringify the dom reference. The html string can be saved and can be used later to append back to the dom.
var string = $('#some-id')[0].outerHTML
Use outerHTML :
document.getElementById('some-id').outerHTML
jQuery clone should do the job. Try this:
var elem = $('#some-id');
var clone = elem.clone();
Besides, why are you saving it to the DB?

JavaScript vs jQuery Selector

I was wondering what the difference between jQuery selectors $("#fake-div) and JavaScript selectors getElementById("fake-div"). First, are these even called JavaScript selectors?. I know jQuery returns the jQuery object whereas JavaScript selectors returns the DOM element; however, given these two blocks of code:
jQuery Selector
var post = $("#postid");
var reply_list = post.find(".replies_ul");
var current_reply = document.createElement("li");
current_reply.setAttribute("class", "reply_li");
reply_list.insertBefore(current_reply, reply_list.firstChild);
JS Selector
var content_list = document.getElementById("content_ul");
var current_post = document.createElement("li");
current_post.setAttribute("class","content_li");
content_list.insertBefore(current_post, content_list.firstChild);
The jQuery Selector ends up removing the list from the DOM when the last line of code is called, and the JavaScript selector successfully inserts the list item at the top of the list. I'm looking for an explanation as to what is going on.
The jQuery insertBefore in your code is invalid, it takes two arguments whereas the jQuery accepts only one:
.insertBefore( target )
Description: Insert every element in the set of matched elements before the target.
And the normal one:
Node.insertBefore
Description: Inserts the specified node before a reference element as a child of the current node.
parentElement.insertBefore(newElement, referenceElement)
The difference is not on the selector but on the method / function that you are calling.
You are using the jQuery insertBefore function and comparing it with the javascript insertBefore function.
In jQuery the insertBefore function has only one parameter and therefore you are using it wrong.
If you want to make use of the Javascript function insertBefore instead of the jQuery one, then you have to convert your jQuery object reply_list to a Javascript one.
You can do this by using .get(0) or [0] like so:
reply_list[0].insertBefore(current_post, content_list.firstChild);
//or like this
reply_list.get(0).insertBefore(current_post, content_list.firstChild);
In your first block of code, the reply_list is a jQuery object; meaning it doesn't actually have a .firstChild property.
Change it to this:
reply_list.get(0).insertBefore(current_reply, reply_list.get(0).firstChild);
Please note the differences between jQuery's insertBefore and JavaScript's insertBefore

Removing $() jQuery wrapper to just get raw JS element [duplicate]

This question already has answers here:
How to get a DOM Element from a jQuery selector?
(4 answers)
Closed 8 years ago.
Random just out of curiosity question:
Let's say for whatever reason I get an element back from a function
$(element)
But I want to remove the $( __ ) jQuery wrapper to leave the regular DOM Element:
element
Is this possible? (I'm sure it'd be smart to test $(element).length() to make sure it isn't more than 1 thing inside beforehand too...
jsFiddle
var firstElem = $(element)[0];
or
var firstElem = $(element).get(0);
Calling get() without an index gives you an array of the elements.
Reference: jQuery get()
DOM elements are stored as properties at numeric zero-based indices, so you access them just like you would for any other object.
$jqObj[0];
Or get a full Array of elements using toArray()
$jqObj.toArray();
Fiddle: http://jsfiddle.net/xHj5d/2/
removeJWrapper($('#ohHeyo'));
function removeJWrapper (el) {
console.log(el[0]);
}

What is the difference between setAttribute and dot notation in Javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When to use setAttribute vs .attribute= in JavaScript?
Why do you sometimes set an attribute like this:
x.type = "submit";
and other times like this:
x.setAttribute("type", "submit");
I always figured it didn't matter which way, but I'm having an issue doing this:
x.onClick = save;
but when I switch it to this it works:
x.setAttribute("onClick", "save()");
setAttribute only works on DOM elements and lowercases the attribute name on HTML elements. And you can't use dot notation to assign values to dynamic attribute names.
And there's also this:
Using setAttribute() to modify certain attributes, most notably value
in XUL, works inconsistently, as the attribute specifies the default
value. To access or modify the current values, you should use the
properties. For example, use elt.value instead of
elt.setAttribute('value', val).

Categories

Resources