jQuery: Object HTMLDivElement, get values?
This code will get you the time and temp values as strings using yourDiv
as a context:
var $div,
time,
temp;
$div = $(yourDiv); //save the div as a jQuery collection
//(assuming `yourDiv` is the actual DOM node)
time = $div
.find('.time') //from the div find the .time descendants
.text(); //get the text from the first .time descendant
temp = $div
.find('.temp') //from the div find the .temp descendants
.text(); //get the text from the first .temp descendant
A more concise way of writing this would be:
var time,
temp;
time = $('.time', yourDiv).text();
temp = $('.temp', yourDiv).text();
In both of these examples I've explicitly chosen .time()
over .html()
in case there are any HTML entities in the values, in your case it won't make a significant difference, but it seems as though you're interested in the parsed value rather than the raw HTML.
If you need the values as numbers, you'll want to cast the string value to a number:
time = Number(time);
a shortcut for this is the unary +
operator:
time = +time;
So the final code looks like:
var time,
temp;
time = +$('.time', yourDiv).text();
temp = +$('.temp', yourDiv).text();
Before using time
and temp
values, be sure to check for NaN
.
If you don't want to use jQuery, you have the native getElementsByClassName()
.
var time = yourDOMobject.getElementsByClassName("time")[0].innerHTML;
Where yourDOMobject
references your [Object HTMLDivElement]
.
Example: http://jsfiddle.net/PhMs4/
Simple enough using jQuery:
var time = $('.time', this).text(),
temp = $('.temp', this).text();
A little longer way that was mentioned in the comments that works as well and shows a bit of chaining methods in jQuery:
var time = $(this).find('.time').text(),
temp = $(this).find('.temp').text();
A mod edited my code which might not be right, since if there is multiple elements with the class of time
and temp
on the page, you could get back the wrong data. My example before edit shows how you can scope the query better:
var time = $('.hour .time').text(),
temp = $('.hour .temp').text();
jQuery.text: http://api.jquery.com/text/