Reputation: 40504
Hello there I have a [Object HTMLDivElement] in which contains data that I would like to use.
I am using this. For example this.innerHTML.
My Div structure looks as the following:
<div class="hour"> <!-- <-- my Object referes to this div -->
<div class="time">2000</div>
<img class="weather-img" src="image/rain.png">
<div class="temp">-10</div>
</div>
I would like to extract the time and temp values, ergo 2000 and -10.
I've been reading the http://krook.org/jsdom/HTMLDivElement.html documentation but cannot seem to find a sleek solution to this, my best bet so far has been innerHTML but feels like there should be a more simple way. Anyone?
ANSWER: var time = $(this).find('.time').text();
Upvotes: 14
Views: 90937
Reputation: 12363
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/
Upvotes: 8
Reputation: 33865
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/
Upvotes: 11
Reputation: 179116
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
.
Upvotes: 1