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>
Related
I'm trying to identify why I cannot get my code to work using JavaScript to wrap all of a specific elements inside a specific div. I've read posts like this one but don't understand why it won't work using the query selector.
So i have this HTML:
<div class='containerA'>
<p>random text</p>
</div>
<div class='containerA'>
<p>random text</p>
</div>
Jquery is loaded in the browser, so using a simple select in JS should work but it fails with the error message shown below:
document.getElementsByClassName('containerA')[0].wrap('<div></div>') // fails "document.getElementsByClassName(...)[0].wrap is not a function"
Also, looping through each element to apply to all using JS fails, presumably for the same reason as the first failure above:
// "el.wrap is not a function"
for (var el of els) {
el.wrap('<div class="testWrap"></div>');
}
// "els[i].wrap is not a function"
for (i = 0; i < els.length; i++) {
els[i].wrap('<div class="testWrap"></div>');
}
// "c.wrap is not a function"
els.forEach((el) => el.wrap('<div class="testWrap"></div>'))
But using jQuery I can get the following to work:
works: $('.containerA').wrap('<div class="testWrap"></div>'); // wraps all elements
works: $('.containerA:first-of-type').wrap('<div class="testWrap"></div>'); // wraps specified element
But using query selector doesnt:
document.querySelector('.containerA:first-of-type').wrap('<div class="testWrap"></div>'); // fails with error "document.querySelector(...).wrap is not a function"
So my main questions are:
How can I wrap individual elements using JS with a loop?
Why does wrap() apply to all elements when wrapAll() presumably should? (my successful JQ code applies to all elements)
Why ever use wrapAll() rather than wrap()?
Presumably wrap() is only for jQuery, but presumably JQ can work with JS, so why wouldn't wrap work after selecting an element using query selector, document get element by class name or any other JS selector?
Any explanation would be much appreciated. Is there something obvious I'm not getting? Thanks for any advice here.
document.querySelector('.containerA:first-of-type') is a valina js HTML object not a jquery's. you have to convert it into jquery object then only you can access jquery's functions.
var container = $(document.querySelector('.containerA:first-of-type'));
container.wrap('<div class="testWrap"></div>');
http://api.jquery.com/wrap/
http://api.jquery.com/wrapall/
Wrap goes around each matching element individually and WrapAll goes around all elements once.
Jquery selector must be used to apply Jquery functions, as the error says, the functions don't exist on the raw elements.
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.
jQuery 1.11.1, on Mac OS X Mavericks, latest version of Safari.
I'm trying to set CSS properties with the css function. css() is missing from elements.
First, I validated that the element is selected correctly:
// There is only one element that has id="container"
var $container = $('#container');
// Selector returns a collection. I have to access first element:
console.log($container[0]); // prints HTMLDivElement
// css function is undefined
console.log($container[0].css); // prints undefined
// Also can't set any css value. Gives undefined error.
$container[0].css({backgroundColor:'blue'});
The error is:
TypeError: 'undefined' is not a function (evaluating
'$container[0].css({backgroundColor:'blue'})')
I removed everything from the test page. It includes jQuery, and within the body it has the div with the ID. Very simple. Beneath that, there is the JavaScript code shown above.
Any idea why the div would be lacking the css function?
It is because you are dropping out of the jQuery object and are using the DOM element...
$container[0].css({backgroundColor:'blue'});
The [0] here gets you the DOM object from the jQuery object.
Use jQuery if you want to access the jQuery method...
$container.css({backgroundColor:'blue'});
You're using jQuery incorrectly. When you say $container[0] you are getting the first javascript DOM element of the jQuery object (which doesn't have any jquery functions attached to it). If you want to get the css background color of the element using jQuery you need to do $container.css("background-color"), and to set it $container.css("background-color", "blue"); or $container.css({ "background-color": "blue" });
Because the css function is a method of a jquery object. When you do $container[0] you get the first DOM node that matched the selector, which is not a jquery object.
Try $container.css(...).
When you access the collection items, no longer has the jQuery methods, only the DOM elements.
You could replace:
$container[0].css({backgroundColor:'blue'});
by
$container.css({backgroundColor:'blue'});
If you have one more div element with the same css attribute,
for instance lets say below statement returns more than one result:
var $container = $('.container'); // Has 3 results
And you want to reach specific elements css attribute then you can revert the dom element into jquery element and do what you want as below:
$($('.container').get(2)).css({ "background-color": "blue" });
http://jsfiddle.net/JNR63/
check this example
alert($container.css("width"));
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>
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)