How can I create a jQuery object from innerHtml? - javascript

I have a string which holds the innerHtml of an object (received via a call to $.html()).
How can I create a jQuery object based on that string?

$(htmlString)
This will hold all of the elements in the string.

If you still have the original jQuery object you called the .html() on, you can access its children directly by using the .children() method:
var $children = $obj.children();
This will return them as jQuery array.

var newelement= $('<div/>');
newelement.html(htmlString);
This differs slightly from SLaks's answer in that it preserves direct text node children. jQuery's $(htmlString) construction shortcut, like many of its features, only deals with Element nodes and not Text nodes.
So if htmlString is 'foo<bar>bof</bar>zot', and you wanted to keep the foo and the zot, you'd have to do it this way.
Similarly with Xion's answer, if you wanted to keep direct text node children, you'd have to use the more-unusual contents() method rather than children().

Related

How to treat the return value of jQuery functions that return a bunch of elements

How to can I treat the return value of jQuery functions that would return a bunch of DOM elements. E.g. I'm using the .nextAll() function, that returns a bunch of elements, does it? Can I store the return value in a JS array? Sooner or later I want to iterate through those elements. I know there's the jQuery .each() function that would help me out here. Nevertheless, for training and understanding issues I first want to do it step by step.
I'm pretty sure, this basic question is answered somewhere, but I searched for an answer and did not find anything useful for me. Maybe I didn't find the right words. So please be kind.
jQuery functions typically returns a bunch of DOM elements, it masquerades as an array.
If you run something like:
$('p').css('background-color', 'red');
jQuery will build an array of all p elements, and then applies the css() function to each of them.
If you want a single DOM item, use get with an index:
$( "li" ).get( 0 )
So, .nextAll() also typically returns a number of elements, so it is behaving just like jQuery typically does.
each() is a handy-dandy function that operates on arrays, so it will of course operate just fine on jQuery objects:
$('li + li').nextAll().each(function(i){
//glorious code
});
You could also do this:
var nexts = $('li + li').nextAll();
$.each(nexts, function(i){
//Glorious code!!
});
Hope that makes things clearer!
You can just assign it to a variable:
var $els = $(selector).nextAll();
This way, $els will be a jQuery wrapper (array-like object) of the elements.
If you want to have an array of the elements instead, you can use
var arr = [].slice.call($els);
As the documentation of .nextall() says, it returns jQuery
A jQuery object contains a collection of Document Object Model (DOM)
elements that have been created from an HTML string or selected from a
document. Since jQuery methods often use CSS selectors to match
elements from a document, the set of elements in a jQuery object is
often called a set of "matched elements" or "selected elements".
The jQuery object itself behaves much like an array; it has a length
property and the elements in the object can be accessed by their
numeric indices [0] to [length-1]. Note that a jQuery object is not
actually a Javascript Array object, so it does not have all the
methods of a true Array object such as join().

Remove all the DOM elements with a specific tag name in Javascript

How can I remove all the elements with a specific tag name using Javascript. For example, I did the following:
var els = document.getElementsByTagName("center");
and it returned an array of all the center elements. How may I remove all these elements?
Coming from Remove all child elements of a DOM node in JavaScript and JavaScript DOM remove element I know that I can loop through els, find the parent of each element and then remove that specific node. But is there anyother way provided by javascript. Like we can do $('center').remove() in jquery and it removes all the elements with center tag. Anything similar to that in Javascript?
With the mention that you still loop over the elements (there is no way to avoid that), you can do this:
Array.prototype.slice.call(document.getElementsByTagName('center')).forEach(
function(item) {
item.remove();
// or item.parentNode.removeChild(item); for older browsers (Edge-)
});
DEMO: http://jsbin.com/OtOyUVE/1/edit
Some notes on slice:
document.getElementsByTagName doesn't return an array, it returns a live list with a length
property. That is why it is needed to first convert it into an array (Array.prototype.slice does that for any object with the length property). By doing that you eliminate the problem of the list being live (gets updated when you change the DOM) and you also get the other array functions to work (like forEach) which have a more functional syntax for looping.
"it returned an array of all the center elements."
Well, it returned an array-like object (a live NodeList or an HTMLCollection depending on the browser).
"How may I remove all these elements?"
You have to loop through the list removing them one at a time as you mentioned later in your question. If you find yourself doing that a lot, encapsulate the looping inside a function so that you don't have to repeat it.
"we can do $('center').remove() in jquery and it removes all the elements with center tag. Anything similar to that in Javascript?"
jQuery is a collection of JavaScript functions, so it can't do anything JavaScript can't do. jQuery's .remove() method (like most other jQuery methods) will loop internally, it just saves you having to think about it. So that comes back to what I already mentioned above, encapsulate the loop/remove code in a function so that you can use it from any part of your code.

jQuery - Get element from array as jQuery element?

If I call
$(".myClass")
I get an array of elements. If I now want to get the first element as jquery element I would do something like this:
$($(".myClass").get(0))
So I wrap the DOM-Element, which I get from the array again with the jQuery operator. Is there a more elegant way to do this? Some get method, which returns a jQuery element for example?
Use the eq() method:
$(".myClass").eq(0)
This returns a jQuery object, whereas .get() returns a DOM element.
.eq() lets you specify the index, but if you just want the first you can use .first(), or if you just want the last you can use (surprise!) .last().
"I get an array of elements."
No you don't, you get a jQuery object which is an array-like object, not an actual array.
If you plan to use jQuery much I suggest spending half an hour browsing through the list of all methods.
Or use the each method to traverse.
$(".myClass").each(function () {
console.log($(this).html())
})

mootools double dollar equivalent in jquery

I have a line of code that uses mootools to get an array of elements with the given selectors
var menuItems = $$('#container .menu');
I need to convert this to jquery but can't find a solution. I have tried jQuery('#container .menu') but it doesn't return an array.
Is there a way to use '.find()' from jquery on the whole document ? (since I don't have a parent element to make it like parent.find()..)
Any other suggestion is also most welcome
With jQuery your statement:
jQuery('#container .menu')
will return a jQuery object that contains all matching elements where you can access the individual DOM elements with array-like syntax:
var menuItems = jQuery('#container .menu');
menuItems.length // gives a count of how many matched
menuItems[0] // the first matching element
// but you can also use jQuery methods on the object
menuItems.hide();
If you want an actual array rather than an array-like object you can use jQuery's .toArray() method:
var menutItemsArray = jQuery('#container .menu').toArray();
Why don't you try one of the jQuery tutorials available at the jQuery website?
If you absolutely need it as an array, rather than working with the jQuery object returned by the selector, take a look at the .toArray() function.

Deriving an HTMLElement Object from jQuery Object

I'm doing a fairly exhaustive series of DOM manipulations where a few elements (specifically form elements) have some events.
I am dynamically creating (actually cloning from a source element) several <select> boxes and assigning a change() event to them.
The change event executes, and within the context of the event, "this" is the HTML Element Object.
What I need to do at this point however is determine a context for this HTML Element Object. I have these objects stored already as jQuery entities in assorted arrays, but obviously
[HTMLElement Object] != [Object Object]
And the trick is that I cannot cast $(this) and make a valid comparison since that would create a new object and the pointer would be different.
So... I've been banging my head against this for a while. In the past I've been able to circumvent this problem by doing an innerHTML comparison, but in this case the objects I am comparing are 100% identical, just there's lots of them. Therefore I need a solid comparison.
This would be easy if I could somehow derive the HTMLElement object from my originating jQuery object.
Thoughts, other ideas? Help. :(
This would be easy if I could somehow derive the HTMLElement object from my originating jQuery object
you don't just mean $("#object")[0] or $("#object").get(0) with 'derive' do you?
Can't you just use $(this).data("something") to keep data on your elements and then check the values later? (That's assuming you can't just give these things plain ol' "id" values.)
Oh also jQuery itself has a "guid" element that you can use (be careful!)
$(myNewObject).data("identity", $.quid++);
If you maintain a jQuery object containing the elements you've created/cloned (let's call it "jqClonedElements"), you can reduce that set to the single element matching "this" with $().filter(element):
var jqThis = jqClonedElements.filter(this);
After this, you may want to confirm that your element was found, as follows:
var elementWasFound = (jqThis.length > 0);
That should be all there is to it!
-Matt

Categories

Resources