Reputation: 1373
I'm trying to get ALL the content of a div as html. This is the script I'm using:
<script>
$('.clickMe').click(function (event) {
var content = $("div#myId").html();
alert(content);
});
</script>
It works when I'm having this html:
<div id="myId" class="clickMe">
some content
</div>
The alert shows: "some content"
But it doesn't work when I do it like this below:
<div id="myId" class="clickMe">
<p>some content</p>
<br/>
<p>some more content</p>
</div>
Then the alert never shows. Note: I want it to alert ALL the html, so the output I want in my second alert example is:
"<p>some content</p><br/><p>some more content</p>"
EDIT:
I think I didn't wrote enough information about my real problem, sorry. The alert works!
But when I'm trying to use var content = $("div#myId").html();
in a AJAX-post it fails, why is that?
When using my first example it works, but not when using the second
Here is my full code:
<script>
$('.clickMe').click(function (event) {
var content = $("div#myId").html();
alert(content);
$.ajax({
url: 'Home/SaveContent',
type: 'POST',
data: {
contentToUpdate: content
},
dataType: 'json',
success: function (data) {
alert("works");
},
error: function () {
alert("error");
}
});
});
</script>
Upvotes: 0
Views: 130
Reputation: 33
I think all the answer provided should be correct. Have you make sure that u have different id on each div.
$('.clickMe').on('click', function(){
alert($(this).html().replace(/(\r\n|\n|\r)/gm,''));
});
if you trying to get the content of clicked content u may want to use 'this' instead of get the content by the id.
see on jsfidle http://jsfiddle.net/71krrfqf/
Upvotes: 2
Reputation: 18873
Instead of $("div#myId").html()
try $("div#myId").text()
OR (Wrap your jquery code inside document.ready()
as shown below)
$(document).ready(function(){
$('.clickMe').click(function (event) {
var content = $("div#myId").html();
alert(content);
});
});
Upvotes: 1
Reputation: 679
Use below script to get content without linebreaks.
$('.clickMe').click(function (event) {
var content = $("div#myId").html().replace(/(\r\n|\n|\r)/gm,"");
alert(content);
});
Hope this helps.
Upvotes: 0
Reputation: 10896
if you want to show html than use
var content = $("div#myId").html();
alert(content); // content not cont
NOTE : use DOM ready function
$(function(){
$('.clickMe').click(function (event) {
var content = $("div#myId").html();
alert(content);
});
})
Upvotes: 0