1

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.

4
  • you need an id somewhere, or at least to know a little more about the page to do this. Commented Jul 21, 2009 at 5:24
  • The Myfunction() is in my control I can send 'this' out there, can this help ? Commented Jul 21, 2009 at 5:32
  • Is there only one child for the div with onclick? Commented Jul 21, 2009 at 5:32
  • sorry I was late, Yes there is only one child Commented Jul 21, 2009 at 6:00

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

3 Comments

The previous answer solves my problem, thanks. The second solution uses div ids, and I dont have the id attr in the divs.
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
ok, then continue with the first block of code. Good luck...
0

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.

1 Comment

will the div[onclick] select all the divs with onclick attribute in it?
0

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')

1 Comment

You missed a single quote in the MyFunction('value');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.