views:

728

answers:

3

I have following structure

<div onClick="javascript:Myfunction('value');">

<div title="Mytitle"> </div>

</div>

Can I access in the javascript Myfunction, the title of the inner div. There are no ids here.

A: 

If it's the only div with the title you can use this selector:

$('div[title]')

The easiest solution would to add a class or id to the div with onClick defined (I suggest moving onlick to JS code as well)

<div class="myClass">
    <div title="MyTitle"> ... </div>
</div>

And in JS:

$('.myClass').click(function() {
    MyFunction('value');
});

Then you can find inner div with

$('.myClass div')
RaYell
You missed a single quote in the MyFunction('value');
rahul
Just fixed that, thanks.
RaYell
A: 

Depends if you use any JavascriptLibraries like jQuery. If you do, you can select your objects via CSS selectors, which would be in your case

$('div[onclick] > div[title]')

You'd get your inner DIV element with it. If there are more elments that match this criteria, you could limit them even more by attribute values.

Robert Koritnik
I will try this
San
will the div[onclick] select all the divs with onclick attribute in it?
San
+1  A: 

If you do not want to change the html code then you can use this.

function MyFunction ( elem )
{
      var child = jQuery(elem).find("div");

      alert ( child.attr("title") );
}


<div onclick="MyFunction(this);">

<div title="Mytitle"> </div>

</div>

Otherwise try this

$(document).ready ( function () {     
       $('#divMain').click(function() {
        var titleElem = $(this).find("div");     
        alert ( titleElem.attr("title") );     
       });
      });

<div id="divMain" style="width: 100px; height: 100px;">
       <div title="Mytitle">
       </div>
      </div>
rahul
Exactly what I wanted
San
The previous answer solves my problem, thanks.The second solution uses div ids, and I dont have the id attr in the divs.
San
Its better to use ids and use the second code
rahul
The hypertext is generated by a calendar displaying library, I dont have much control on it. But I have a option to provide the javascript when a use clicks on a cell in the calendar
San
ok, then continue with the first block of code. **Good luck...**
rahul