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 access that span based on that event, because I have may <div class="feeds"> elements.

Even a JQuery suggestion is welcome.

Thank you.

link|flag

3 Answers

up vote 1 down vote accepted

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.

link|flag

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.

link|flag
Thank you guys. It worked. Just one last thing. How do I flag this post as answered? Is it possible/necessary? Im new in SO. – Sthe 2 hours ago
@Sthe Just click the tickmark on the left of the question you like most. – bazmegakapa 2 hours ago

Somethink like this?

$('.feeds').mouseover(function() {
  $('span',this).html();
});
link|flag

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.