jQuery removes wrapping element - javascript

I am loading a html file with jquery $.get and wrap the response. But jQuery removes my wrapper .
I made the following example which demonstrates my problem:
https://jsfiddle.net/pwm76bp6/
Everyone who dont want to open the link here is the example code:
alert($('<div><div>Hallo</div></div>').html());
I would expect that the whole string should be alerted. Whats the problem here?

You need to read outerHTML property.
console.log($('<div><div>Hallo</div></div>').prop('outerHTML'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Dynamically wrap it with an element, then get the html() of the wrapped element.
alert($('<div><div>Hallo</div></div>').wrap("<div></div>").parent().html());

It doesn't remove your wrapper. jQuery html() does return the contents of an element.
When you do $('<div>my content</div>') you creating an element, then you get the inner html with html() which is then alerted in your example.

With your code you will get the html of your outer element <div>. And the content of the outer <div> is <div>Hallo</div>.
You can do what you want with a default property:
alert($('<div><div>Hallo</div></div>')[0].outerHTML);

the function "html" does return the html content of a given element. In your case "html()" returns the content of the outer div, which excludes the outer itself.
You may can overcome this by wrapping your html like:
var html = '<div><div>Hallo</div></div>';
var outerHtml = $(html).wrap('<div />').parent().html();
hope this helps.

Related

How can I chain .html() and .fadeIn() in jQuery?

Here is my code:
$('.container-modal-cash').html().fadeIn(1500);
It throws:
Uncaught TypeError: $(...).html(...).fadeIn is not a function
Why? And how can I fix it?
Generally I'm setting a content (using .html) inside an element and then showing it (using .fadeIn). What's wrong?
This thing only works when you set some html inside html function.
$('.container-modal-cash').html("testing fadeIn").fadeIn(1500);
//below will fail with same error - uncomment below code to verify
//$('.container-modal-cash').html().fadeIn(1500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-modal-cash"></div>
The .html() can be used to set the contents of the element, or get the contents of the element. FadeIn/Out methods work on the Jquery selector element ( I mean $('.test') ).
Courtesy of Trincot, you can also use the fadeIn/fadeOut() methods, when you set the content of the element using html().
$('.test').html("final content").fadeOut(1500).fadeIn(1500);
please refer the below example demonstrating this.
console.log("getting the contents inside");
console.log($('.test').html());
console.log("setting the contents inside");
$('.test').html('changed content');
//fade works on the JQuery selector element.
$('.test').fadeOut(1500);
$('.test').fadeIn(1500);
// you can chain the fadeIn/fadeOut methods like so
$('.test').fadeOut(1500).fadeIn(1500);
// you can also chain the fadeIn/fadeOut when setting the html content like so.
$('.test').html("final content").fadeOut(1500).fadeIn(1500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">content</div>

JS: Moving an anchor with insertAdjacentHTML only appends the href, not the element

I'm trying to move an anchor tag from one element to another. When I do this, the only thing appended is the anchors href, not the element itself. Why is this and how can I fix it?
I need a solution in Javascript only as jQuery isn't being used
Thanks for any help!
Fidde: https://jsfiddle.net/p7g7mkxs/
What I've tried:
<p class="hello">hello</p>
<p class="hello">helloLINK</p>
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0]);
I've also tried using different variations of selecting my elements, like getElementsByTagName or appending it differently with innerHTML - Everything I've tried has given me the same result.
You use insertAdjacentHTML with HTML (a string), not with an actual element. If you pass it an element, the element is converted to string (like String(theElement)). In the case of an HTMLAnchorElement, that means you just get the href. Proof:
console.log(
String(document.querySelector("a"))
);
Hey
To append an element to the end of another element's child list, use appendChild:
var hello = document.querySelectorAll('.hello');
hello[0].appendChild(hello[1].querySelector('a'));
(To insert it elsewhere, use insertBefore. Actually, you can use insertBefore in all cases if you like, just use null as the reference element when adding to the end.)
Also note that when you only want the first match, rather than querySelectorAll(/*...*/)[0], use querySelector(/*...*/), which returns the first match or null.
In addition to what #t-j-crowder said, you can also use outerHTML to accomplish the task:
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0].outerHTML);

Find <style> tag by class not working

I'm using AJAX to fetch some HTML markup. I want to append some style tags (with a class) from the fetched markup to my own document using find(). However, jQuery does not seem to like the following approach.
(link removed due to lack of reputation)
Could someone shed some light on why this does not work, and point me in the right direction?
Thank you in advance.
Solutions
Making it a native element first (and removing script tags as extra precaution) works. http://jsfiddle.net/T6QCR/5/
Also, a lot simpler, using innerHTML instead of .html() works, as setting innerHTML does not evaluate scripts and allows .find() to function. http://jsfiddle.net/T6QCR/8/
Also, laconbass' answer below.
Thank you for the help!
Parse the HTML chunk rather than just passing it to jQuery
From the jQuery function documentation for the case you are using:
(...) if the string appears to be an HTML snippet, jQuery attempts to
create new DOM elements as described by the HTML. Then a jQuery object
is created and returned that refers to these elements. You can perform
any of the usual jQuery methods on this object.
(...)
If the HTML is more complex than a single tag without attributes, as
it is in the above example, the actual creation of the elements is
handled by the browser's innerHTML mechanism. In most cases, jQuery
creates a new element and sets the innerHTML property of the
element to the HTML snippet that was passed in.
(...)
When passing in complex HTML, some browsers may not generate a DOM
that exactly replicates the HTML source provided. As mentioned, jQuery
uses the browser"s .innerHTML property to parse the passed HTML and
insert it into the current document. During this process, some
browsers filter out certain elements such as , , or
elements. As a result, the elements inserted may not be
representative of the original string passed.
The documentation recomends ussing $.parseHtml()
For explicit parsing of a string to HTML, use the $.parseHTML()
method.
$.filter rather than $.find
As you noted, $.find does not work on this example. I had succeed replacing it with a $.filter call.
// this works
$html.filter('.test');
// this doesn't works
$html.find('.test');
// better if you filter also by tag
// surely you will have more tags other than <style> on the retrieved html
$html.filter('style.test');
See how this applies to your example on this fiddle.
body is not defined, the console gives an indication of this by way of an error, too. If you want to use jQuery to select the markup body and append the style then you will need to use an appropriate selector:
$("body").append($style);
<style> element can't has class attribute, because Uncaught SyntaxError: Unexpected identifier.
This code shoud work:
var html = '<html><head><style>aaa</style></head></html>';
var $html = $.parseHTML(html);
$.each($html, function(i, el) {
if(el.nodeName == "STYLE") {
$("head").append(el.outerHTML);
return false;
}
});
I'm not really sure as to why this is, but it has something to do with the document model and how it works. You can't just hold a temporary var with the html text in it, you need to put it all inside an element (like a div) that is attached to the document in some way. This div could be hidden from view from the user.
<html>
<head>
<div></div>
</head>
<body>
<script>
jQuery(document).ready(function($) {
$('div').hide().html('<html><head><style class="test"></style></head></html>'); // From AJAX request
var $style = $('div').find('.test');
document.body.appendChild($style[0]);
});
</script>
</body>
</html>

javascript - innerHTML in <span> in iframe wont change html

I am trying to change HTML code within an IFrame (it's on the same domain), but for some reason, this line, wont change the html:
$('iframe').contents().find('#weergave_afstand').innerHTML = afstand
the text it should modify is the following:
Afstand traject: <span id="weergave_afstand">200</span> km.
But for some reason, it doesn't.
When I use
$('iframe').contents().find('#weergave_afstand').html()
it reads the value (200) just fine...
What am I doing wrong here?
innerHtml is not a jQuery function, it is an HTMLElement Property.
Usage --> http://www.tizag.com/javascriptT/javascript-innerHTML.php
To write to the inner html using jquery you can use the same html() function which you used for read.
$('iframe').contents().find('#weergave_afstand').html(afstand);
innerHTML is not a jQuery method. You can change the innerHTML property by putting the value in the html() method like this:
$('iframe').contents().find('#weergave_afstand').html("afstand");
Hope that helps!

Prototype.js get text from an element

I'm new to Protoype.JS and just testing it a bit because I heard it was good, but I'm stuck quite quickly.
As easy as this is with jQuery, it seems to be the end of the world to get the text in an element. I've tried innerHTML in multiple ways but the only thing I can get is "undefined".
alert($$('.mnu_item').innerHTML);
alert($('content').innerHTML);
None of these work.
Content is a div with id "content" and .mnu_item is an anchor tag with class ".mnu_item".
I don't get what the problem is, probably something stupid but it would be great if somebody could point me in the right direction!
EDIT: I've found that it isn't the innerHTML that doesn't work but it's the class selector. The second line in the code above does work. How can I select an element by its class in the latest Prototype version if this isn't the correct way?
Has the DOM loaded when you run your script? If you're not running this code in a window.onload or by placing it at the end of the body, then the elements by not exist when it runs.
Try placing your script just inside the closing </body> tag.
<body>
<!-- my content -->
<script type="text/javascript">
alert($('content').innerHTML);
</script>
</body>
Also, your first line is selecting correctly, but will return an Array of elements, so innerHTML will be undefined.
To iterate the Array, you can do this:
$$('.mnu_item').each(function(val,i) {
alert(val.innerHTML);
});
or if you want to end up with an Array of the innerHTML values, do this:
var values = $$('.mnu_item').map(function(val,i) {
return val.innerHTML;
});
Make sure the DOM is loaded before you run these tests:
$(document).on('dom:loaded', function () {
/* code to execute after dom has loaded */
})
The first line of code $$('.mne_item') doesn't work because $$ gives back an array of all elements matching the css rule. So $$('.mne_item') gives an array of all dom elements which has the class mne_item. You can ask the first one by using the first method or iterate over all items like this:
$$('.mne_item').each(function(elem) {
// elem is the li elements extended by all Element methods of prototype
});
If you use $ in jQuery, it actually uses a similar pattern but hides the each construct. It just applies the chained method to all elements or just the first.
The second line of code $('content').innerHTML should work. $ is a shortcut for document.getElementById so it should give you a DOM node back. The reason why this doesn't work is there is no node where id = content, probably because the dom isn't loaded yet.
For more info about the methods of prototype look at the api: http://api.prototypejs.org/
Also check the default DOM methods: http://quirksmode.org/dom/w3c_core.html
$('content').innerHTML should work. Check your HTML, ensure the ID is unique.
var text = $$('label[for="display_on_amazon"]').first().textContent;
Above code worked for me.
Regarding, $$('.mnu_item').innerHTML
When you are trying to fetch with class selector, prototype returns array of multiple elments, by using [0] or first() method system will point at the first element in that array, after that you can use innerHtml (to get html inside the element) or textContent (to get text content of that element, native javascript method)

Categories