I have a textarea, inside this textarea, dynamic HTML content are bind like
<div id="HDWebAllTemplateHTMLListMessage">
<div id="header">This is a header</div>
<div class="main">
<div id="content">This is my main content.</div>
<div id="sidebar">This is a sidebar</div>
</div>
<div id="footer">This is my footer</div>
</div>
Somehow i want html content inside .main class. I tried but not able to get html content.
var textAreaContent=$($('#HDWebAllTemplateHTMLListMessage').text());
var divContent=textAreaContent.find('.main');
console.log(divContent.innerHTML);
3 Answers 3
Do you really need to use textarea?
You can try like below. But if you don't need it. The azizsagi example is working fine.
JAVASCRIPT
var newdiv1 = $("<div class='dummy'></div>");
$("textarea").after(newdiv1); /* create dummy div */
var tgt = newdiv1;
var main = tgt.html($("textarea").text()).find(".main").text();
tgt.text(main);
/* newdiv1.remove(); */ // If you want to remove the element after you get what you need
JSFiddle : https://jsfiddle.net/synz/amgtLwex/
Comments
text()
gives you the text content, not the html, so it won't work to wrap it in $()
. Use html()
.
$('#HDWebAllTemplateHTMLListMessage .main').html()
Comments
You can get the result by changing your js script to follows
<script>
var textAreaContent=$('#HDWebAllTemplateHTMLListMessage > .main').html();
console.log(textAreaContent);
</script>
here is running example
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="HDWebAllTemplateHTMLListMessage">
<div id="header">This is a header</div>
<div class="main">
<div id="content">This is my main content.</div>
<div id="sidebar">This is a sidebar</div>
</div>
<div id="footer">This is my footer</div>
</div>
<script>
var textAreaContent=$('#HDWebAllTemplateHTMLListMessage > .main').html();
console.log(textAreaContent);
</script>
</body>
</html>
#HDWebAllTemplateHTMLListMessage
is nowhere in the code you posted, nor is.23TC
, and what ishtmlContent
?#HDWebAllTemplateHTMLListMessage
?find()
function returns a jQuery object, and it doesn't have a property namedinnerHTML
, usehtml()
instead. Also, jQuery'stext()
function doesn't returns the HTML tags - again, usehtml()
instead. See jQuery Docs.