I have a string (resultString) that contains long html codes. These codes are grouped in 2 main DIVs, window and Popup.
resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>"
Now I want to retrieve the html content of window and popup DIVs separately and place them in 2 different strings (stringWindow and stringPopup).
stringWindow = "<div id=\"window\">window content --- long html codes</div>";
stringPopup = "<div id=\"PopUp\">Popup content --- long html codes</div>";
Is there any simple way to do so in jQuery/javascript? The stringWindow is constructed in an Ajax json webmethod function. Any help is well appreciated! Thanks in advance.
You can use filter()
and outerHTML
filter
you can filter element with certain selectorouterHTML
for getting html contentvar resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>",
stringWindow, stringPopup;
stringWindow = $(resultString).filter('#window')[0].outerHTML;
stringPopup = $(resultString).filter('#PopUp')[0].outerHTML;
console.log(stringPopup, stringPopup);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Trivial in jQuery:
var resultString = "<div id=\"window\">window content --- long html codes</div><div id=\"PopUp\">Popup content --- long html codes</div>"
var $doc = $("<div>" + resultString + "</div>");
var stringWindow = $doc.find('#window').text();
var stringPopup = $doc.find('#PopUp').text();
console.log("window", stringWindow);
console.log("popup", stringPopup);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Not much harder in plain JS.
If by "Just the content" you don't mean "text" but markup inside the div, then replace text()
with html()
.
EDIT: made into executable snippet.
A version that doesn't use jQuery, doesn't assume it is in the document or can be put into the document but still interprets it as HTML -
var domParser = new DOMParser(),
doc = domParser.parseFromString(resultString, "text/html"),
content = ["window", "PopUp"].map(function(id) {
return doc.querySelector("#" + id).innerHTML;
}),
stringWindow = content[0],
stringPopup = content[1];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With