This is actually two question. I was playing around with the .eq method in jquery and decided to test it out using jsfiddle. What puzzles me is that when I supply an index that is obviously out of bound it still returns me an obj instead of an index out of bound error.
console.log($("body").children("div").eq(2));
console.log($("body").children("div").eq(20));
So I did this using the .children method from jquery. Upon closer inspection if I specify a selector it gives me the correct children, but if I do not it also returns the title element which is outside of the body.
console.log($("body").children());
console.log($("body").children("div"));
Does anybody know why? Here is the jsfiddle
No Index out of bounds
This was just a choice of the jQuery developers. If a selector returns no results, it will be an empty jQuery collection rather than return an error.
$("body").children("div").eq(20).length === 0
<title> appears in <body>
jsfiddle.net automatically has <html>, <head>, and <body> elements. Everything in the HTML frame is already wrapped in <body>. The <body> you provide is ignored. I do find it odd that <title> ends up being acceptable there, though.
At least in the case of your jsfiddle, jsfiddle automatically injects everything you type in the html area into a body tag, this your example ends up rendering something like the following, so as you can see, title IS a child of body.
<html>
<head>
</head>
<body>
<title></title>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
Related
Using the code below, I am successfully getting the jQuery.load to pull the external element's html into the div ("tnc-import"), but according the console, the newElementHeight variable just returns the init information of the element (init [prevObject: init(1), context: document, selector: "div#tnc-import > div#tnc"]) instead of actually getting the true-height attribute of the external element.
The source document includes the text to be imported inside <div id="tnc">...</div>. The target document includes...
<div>
<iframe id="iframe" src="/bin/tnc-import" frameborder="0" scrolling="no"></iframe>
</div>`
The intermediary document doing the importing and formatting is...
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
</head>
<body>
<div id="tnc-import"></div>
</body>
<foot>
<script type='text/javascript'>
$("#tnc-import").load( "../terms-and-conditions #tnc" );
var newElementHeight = $("div#tnc-import > div#tnc").height(true);
console.log(newElementHeight);
$('#iframe', window.parent.document).width('100%');
$('#iframe', window.parent.document).height(newElementHeight);
</script>
</foot>
</html>
The reason why I'm trying this is that all attempts to get the height, clientHeight, offsetHeight, etc of the jQuery-loaded element always result in "0". I've literally spent more than 12 hours troubleshooting with Google on this one objective, but with no positive result. Perhaps there is something wrong with that script that I've just not noticed... Either way, neither method or any variation that I've tried has worked.
Here is one of the old method variants that I was trying...
<script type='text/javascript'>
$('#iframe', window.parent.document).width('100%');
$('#iframe', window.parent.document).height($("div").outerHeight() + 10);
</script>
According to the documentation of jQuery, .height() does not accept any arguments with Boolean parameters, try removing true from the function to receive height in newElementHeight element.
Reference :http://api.jquery.com/height/
I don't know how to declare a variable here in javascript. I have an example situation that if the paragraph is equals to a, the alert will popup.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="sample">a</p>
</body>
</html>
<script type="text/javascript">
var sample = getElementById('sample');
if (sample == "a") {
alert("Correct")
};
</script>
You're declaring your variable just fine, however if you want the text within the element, you also need to use the innerHTML property. And when you use the getElementById method, you need to use it on the document object like document.getElementById:
var sample = document.getElementById('sample');
if (sample.innerHTML == "a") {
alert("Correct")
};
<p id="sample">a</p>
sample is a variable and you are correct but it is storing a reference to a DOM Element with id sample. To get the inner html of that you need
var sample = getElementById('sample').innerHTML;
Also, use === over == for no casting etc. Refer here
I will recommend you to have a quick look at JS from w3schools and then move to MDN. Nobody will report you here if you show your efforts, so relax :).
Your declaration is fine, but the assignment part is missing document as the object which has the .getElementById method. Then, once you have the reference to the element, you then need to access its content with .textContent (you can't compare the entire element to a value that the element might contain). As a side note on this, when the string you wish to set/get doesn't contain any HTML, you should use .textContent so that the browser doesn't parse the string for HTML unnecessarily. Often, people will suggest that the content of an element should be gotten/set using .innerHTML and, while that will work, it's wasteful if the string doesn't contain any HTML.
Also, the <script> must be located within the head or the body, not outside of them. I would suggest placing it just prior to the closing body tag so that by the time the processing reaches the script, all of the HTML elements have been parsed into memory and are available.
Lastly (and this is really just a side point), an HTML page also needs the title element to have something in it, otherwise it won't be valid. While browsers don't actually do HTML validation, it's important to strive for valid HTML so that you can be sure that your pages will work consistently across all devices. You can validate your HTML at: http://validator.w3.org.
<!DOCTYPE html>
<html>
<head>
<title>Something Here</title>
</head>
<body>
<p id="sample">a</p>
<script type="text/javascript">
var sample = document.getElementById('sample');
if (sample.textContent == "a") {
alert("Correct")
};
</script>
</body>
</html>
I would like page.html to ajax-request the content of side.html and extract the content of two of its divs. But I cannot find the correct way to parse the response, despite everything I tried.
Here is side.html:
<!DOCTYPE html>
<html>
<head>
<title>Useless</title>
</head>
<body>
<div id="a">ContentA</div>
<div id="b">ContentB</div>
</body>
</html>
and here is page.html
<!DOCTYPE html>
<html>
<head>
<title>Useless</title>
<script type='text/javascript' src='jquery-1.9.0.min.js'></script>
</head>
<body>
Hello
<script type="text/javascript">
jQuery.ajax({
url: "side.html",
success: function(result) {
html = jQuery(result);
alert(html.find("div#a").attr("id"));
alert(html.find("div#a").html());
alert(html.find("div#a"));
},
});
</script>
</body>
</html>
When I access this page, I get no error, and the three alert()s yield undefined, undefined and [object Object]. What am I doing wrong? Example is live here.
You need to change this line:
html = jQuery(result);
To this:
html = jQuery('<div>').html(result);
And actually, even better you should declare this as a local variable:
var html = jQuery('<div>').html(result);
Explanation
When you do jQuery(result), jQuery pulls the children of the <body> element and returns a wrapper around those elements, as opposed to returning a jQuery wrapper for the <html> element, which I tend to agree would be pretty dumb.
In your case, the <body> of sidebar.html contains several elements and some text nodes. Therefore the jQuery object that is returned is a wrapper for those several elements and text nodes.
When you use .find(), it searches the descendants of the elements wrapped by the jQuery object that you call it on. In your case, the <div id="a"> is not one of these because it is actually one of the selected elements of the wrapper, and cannot be a descendant of itself.
By wrapping it in a <div> of your own, then you push those elements "down" a level. When you call .find() in my fixed code above, it looks for descendants of that <div> and therefore finds your <div id="a">.
Comment
If your <div id="a"> was not at the top level, i.e. an immediate child of the <body>, then your code would have worked. To me this is inconsistent and therefore incorrect behaviour. To solve this, jQuery should generate the container <div> for you, when it is working its <body> content extraction magic.
Try this :
$.get(url,function(content) {
var content = $(content).find('div.contentWrapper').html();
...
}
I have a problem getting the height of a (the one in the code below, with class="post_div"). And I want to return with a document.write whitin the HTML body - maybe later using it as height for other elements, that I want to be equal. I have tried every possible code for getting the height of such an element, but every time it returns 'undefined'. I have also tried setting height=auto for the DIV. I am almost sure my problem not has to do with the way I get the height, but have no other idea for what else it could be! Therefore I have choosen to bother you with the full structure of my coding. The JavaScript is placed in a separate document containing only the following statement:
var result=document.getElementById('postHeight').offsetHeight;
My HTML document looks like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<head>
<title>...</title>
<link rel="stylesheet" type="text/css" media="all" href="C:\Users\Lasse\Desktop\hg2\hg2.css" />
<script src="C:\Users\Lasse\Desktop\hg2\hg2.js"></script>
</head>
<body>
<script>document.write(result)</script>
<div id="postHeight" class="post_div">
...
</div>
</body>
</html>
Hope you can help! Thanks!
There is no element with the ID postHeight. Perhaps you meant
var result=document.getElementById('content').offsetHeight;
Additionally, this calculation must be done after the element you are calculating has been loaded (so either by putting the <script> after the element, or deferring execution with onload or similar).
Since your script tag occurs before the element exists in the DOM, you can't get the height. You could put an event handler waiting for the document to load before getting the height or move that script to the bottom of the page, but your document.write would still be called before the element existed. You need to rethink your design.
Sample code:
<div id=getme>
some text to give it height.
</div>
<script>
document.write(document.getElementById("getme").clientHeight);
</script>
I've searched an answer to this question but can't get a way how to do it.
I want to access the content of a div that I have included in an object tag.
My include.htm file:
<div id="includedDiv">This is the included page</div>
What I have tried :
<html>
<head>
<title>Get element from object included page</title>
</head>
<body>
<p>Test: This is the main page</p>
<object id="obj" data="include.htm"></object>
<script>
//alert(document.getElementById("includedDiv").firstChild.nodeValue);
//alert((document.getElementById("obj")).document.getElementById("includedDiv").firstChild.nodeValue);
alert(document.getElementById("obj")["includedDiv"]);
</script>
</body>
</html>
None of the alert prints me the message "This is the included page", is there a way to get this content from the DOM?
EDIT:
window[0].document.getElementById("includedDiv").firstChild.nodeValue; was the the good answer for access through the DOM, object tag just creates another window :)
http://www.w3schools.com/jsref/prop_win_length.asp
Got it! Just use
window.parent.mainPageMethod(document.getElementById("includedDiv").firstChild.nodeValue);
in the included page and you can get div content in a Javascript function from the main page!
Thanks for trying to help Jay, I should admit that when you talked about window.name property it put me on the right direction :)
document.getElementById('id').innerHTML or document.getElementById('id').outerHTML whichever you are looking for...
see how to append to a object with innerHTML
Even better answer: you CAN access object tag content through the DOM, it is just another window!
window[0].document.getElementById("includedDiv").firstChild.nodeValue;
That's it :D http://www.w3schools.com/jsref/prop_win_length.asp