-11

First Case:

<div>
  <a href="#" onclick="doIt(this)">some job</a>
<div>

i can do:

<script>
  function doIt(caller){
       alert($(caller).closest('div').html());
  }
</script>

Second Case:

<div id="divId">
  ....
</div>

i do

<script>
  alert($("#divId").html());
</script>

how can i apply first case mecanism to second case with out onclick(this)?

more details about question:

First case, as i use of anchor onclick, i can get action source then it's parent.

Second case, on the other hand, there is div block and after script block. they are rendered in the page, consequence there is no click event. i need some thing:

$(this).closest('div').html()

but it doesnt work

1
  • 2
    Could you rephrase your question to make it more clear what you are actually trying to do? It does not make much sense to me... Commented Feb 8, 2011 at 10:41

4 Answers 4

9

I assume you mean something like this?

<script type="text/javascript">
$(document).ready(function() {
   $("#MyLink").click(function() {
      alert($(this).closest('div').html());
   });
});
</script>

This requires you to add id to the link.

If you mean show the alert without clicking anything you'll have to explain how exactly you want it to show, meaning in response to what event?

Edit: in case you have more than one element, use class instead e.g. <a class="MyLink" ...> then have such code:

$(document).ready(function() {
   $(".MyLink").click(function() {
      alert($(this).closest('div').html());
   });
});

Using . instead of # will give all elements with that class.

0
2

Try:

 $("#divId").click(function() {doIt(this);});

Put this on documentReady.

1
$('#divId').click(function() { alert($(this).html()); });
0
1

Simply put it in $(document).ready(); It will then execute when your document is loaded. Something like this:

$(document).ready(function(){
    alert($("#divId").html());
});

Edit (see comment):

$(document).ready(function(){
    $('.yourdivclass').each(function() {
        alert($(this).html());
    });
});
0

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