I am a beginner when it comes to javascript/jquery..so if this question sounds silly,please forgive me.
While going through this tutorial ,I tried to write to javascript console ,values of some of the variables in the functions-so that I can better understand how the function works
$(document).ready(function(){
$("div.post h2 a").click(function () {
var a = $(this),
href = a.attr('href'),
content = a.parent().next();
console.log('a='+a);
console.log('a.get(0)='+a.get(0));
console.log('a parent='+a.parent());
console.log('a parent.get(0)='+a.parent().get(0));
console.log("href="+href);
console.log('content='+content);
content.load(href + " #content");
return false;
});
I have modified the html slightly
<div class="post">
<h2 id="h21"><a href="other/mypage.html">My Page</a></h2>
<div class="content">
Teaser text1...
</div>
</div>
<div class="post">
<h2 id="h22"><a href="other/myotherpage.html">My Other Page</a></h2>
<div class="content">
Teaser text2...
</div>
</div>
});
when I click on the first link,I get this console log output
a=[object Object]
a.get(0)=file:///home/me/dev/misc/other/mypage.html
a parent=[object Object]
a parent.get(0)=[object HTMLHeadingElement]
href=other/mypage.html
content=[object Object]
I thought the $(this) expression in the function would be the element which was clicked(ie the first <a element).Why does it appear as [object Object].I couldn’t make out how a.get(0) becomes file:///home/me/dev/misc/other/mypage.html
Similarly,shouldn’t the variable content be equal to the first div (containing Teaser text1)? Why does it appear as [object Object]?
The variable
acontains a jQuery object, and thetoStringmethod isn’t overridden for it, so it uses the default implementation that returns the type of the object.The
getmethods returns DOM element objects from the jQuery object, and thetoStringmethod for an<a>element returns the URL that the link points to.The variable
contentcontains a jQuery element that contains the<div>element. Usingcontent.get(0)would give you the DOM element.