0

I am trying to automatically get the content in #mydiv when I load a page. Since the content is dynamically, so I just use .on(). It works when I click the #mydiv.

But can it work without clicking the #mydiv? It will be nice if it loads automatically.

$( "#mydiv" ).on( "click", function() {
  alert( $( this ).text() );
});

I have tried "load", but didn't get any luck...

sampathsris
  • 21,564
  • 12
  • 71
  • 98
Pluto
  • 313
  • 1
  • 8
  • 19

6 Answers6

1

Try this:

$(function(){
  alert($( "#mydiv" ).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv" > Some Text </div>
Amy
  • 4,034
  • 1
  • 20
  • 34
1

Why do you need to do this specifically with jQuery? Browsers already has means to call some JavaScript code on page load:

<body onload="alert($('#mydiv').text())">

Or,

<body onload="alert(document.getElementById('mydiv').innerText)">

Above two will do the same.

Any code you specify between a <script> tag will get executed just when the script tag is loaded.

<script>alert($('#mydiv').text());</script>

And if you want to call a function when innerHTML of an element is changed, you should take a look at these questions:

Community
  • 1
  • 1
sampathsris
  • 21,564
  • 12
  • 71
  • 98
0

do you mean this?

$(function() {
    alert( $( '#mydiv' ).text() );
});

that will alert the contents of #mydiv as soon as the page finishes loading and is fully available.

Nicolas Straub
  • 3,381
  • 6
  • 21
  • 42
0

You probably meant trigger()

eg.

$( "#mydiv" ).on( "click", function() {
   alert( $( this ).text() );
});


$( "#mydiv" ).trigger('click');
LJ Wadowski
  • 6,424
  • 11
  • 43
  • 76
0

Try the jQuery trigger method

Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs.

$( "#foo" ).on( "click", function() {
  alert( $( this ).text() );
});
$( "#foo" ).trigger( "click" );

In this example the foo click event is triggered.

svnm
  • 22,878
  • 21
  • 90
  • 105
0
$(document).ready(function()
{
    alert($("#mydiv").text())
})
user619271
  • 4,766
  • 5
  • 30
  • 35