Reputation: 2952
I want to use some jQuery on a website.
I first wrote a tiny static test page only containing the relevant elements to be able to focus on the jQuery part. My script eventually works fine on this test page.
Next I tried to run this script on a (local) WordPress site. Now the script does not work and the particular problem seems to be that it doesn't find any h2
elements.
When I add
(function(){
console.log("I'm here!!");
jQuery('html').css('background','green');
})();
the console logs correctly and the background becomes green so it seems both jQuery as well as my script are loaded correctly.
Now when I add
(function(){
var anchorH2 = jQuery('h2');
console.log(anchorH2.text());
})();
an empty string is printed back to the console. On my test page the h2
text is correctly printed back, though.
I believe that (function(){})
is short for jQuery(document).ready
so I think the DOM not being fully loaded can't be the problem either.
I'm getting one syntax error under JS
in the console: SyntaxError: Using //@ to indicate source map URL pragmas is deprecated. Use //# instead
. However, I get this same error on my test page on which my script works so I'm not sure whether it has any relevance for the problem at hand.
Here's part of my DOM (the selector should be div.excerpt h2
but I replaced it by h2
for testing purposes.
Could anybody please suggest what I'm misunderstanding or overlooking here?
Upvotes: 0
Views: 125
Reputation: 1277
Because when you select elements by tag name (h2 in your case) jquery returns an array of elements (because there can be multiple elements with h2 tag on the page). So running a text() function on an array of elements returns undefined.
Try running the text() function on the 0th element (or iterate over all elements) and it would work
(function(){
var anchorH2 = jQuery('h2');
console.log($(anchorH2[0]).text());
})();
Here is the fiddle http://jsfiddle.net/RKks8/1/
Upvotes: 0
Reputation: 239521
I believe that (function(){}) is short for jQuery(document).ready so I think the DOM not being fully loaded can't be the problem either.
No, that is not the case. The shorthand involves passing a function to the $
(or jQuery
) function:
$(function () { });
// or
jQuery(function () { });
What you've written is an IIFE:
(function () { })();
These are very different, and the IIFE has nothing to do with jQuery or the DOM being ready.
Upvotes: 2