Select specific child of the current element using THIS
I would like to know how can I select <span ="data">
from the following.
<div class="feeds" onmouseover="...">
<div id="someDiv"></div>
<div class="moredivs"></div>
<span ="data">data in here...</span>
</div>
I would like to use something like: onmouseover="select(this)"
and then be able to a开发者_如何转开发ccess that span based on that event, because I have may <div class="feeds">
elements.
Even a JQuery suggestion is welcome.
The HTML you have provided is invalid. When defining attributes, you have to give them a name. Let's assume you have this:
<span class="data">data in here...</span>
With jQuery, you can simply do this without an inline event handler. In your $(document).ready()
you could put:
$('.feeds').mouseover(function () {
var $span=$('span.data', this);
});
$span
will hold access to your span
(in a jQuery collection).
jsFiddle Demo - jQuery version
If you need a Javascript only solution (with your inline event handler: onmouseover="select(this)"
), you would go with something like this:
function select(me) {
var span=me.getElementsByClassName('data')[0];
}
getElementsByClassName()
is only available on modern browsers, but you can use a fallback as well for ancient IEs.
jsFiddle Demo - Plain Javascript / Inline handler
Note: If you have more than one .feeds
, please consider using a class instead of an id for someDiv
, because an id can only appear once in a HTML document.
Working example - http://jsfiddle.net/4NAJ9/1/
<script>
$(function(){
$('.feeds').hover(function(){
var data_span = $(this).find('.data');
alert(data_span.html());
}, function(){
// If you wanted something to happen 'onmouseout', put it here
});
});
</script>
<div class="feeds">
<div id="someDiv"></div>
<div class="moredivs"></div>
<span class="data">data in here...</span>
</div>
If you're willing to use jQuery, then you really don't want to be adding an inline onclick
event to each .feeds
element.
It's better to keep your Javascript separate from your HTML - jQuery allows you to do this easily.
Something like this?
$('.feeds').mouseover(function() {
$('span',this).html();
});
精彩评论