简体   繁体   中英

Jquery -Issue to get div content as html

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>

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/

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);
    });
});

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);
    });
})

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM