Athapali
Athapali

Reputation: 1089

How to get text of element in a variable using jquery?

var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">&#160;</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow <a href="/Shared%20Documents/EBS%20Page%20Refresh%20Instructions_rkc.pdf">these instructions</a>. &#160;</div>';           
var str = "";
$(markup).find("div[class^='ExternalClass']").each(function(){
    str += $(this).text();
})

How do I grab content of all the divs in the markup that starts with ExternalClass?

Upvotes: 1

Views: 3052

Answers (2)

Mohammad
Mohammad

Reputation: 21499

$(markup) selector contain all ExternalClass class and you can't use .find() because it doen't any matched child. You need to use .filter() to filter selected element.

var markup = "<div...";
var str = "";
$(markup).filter("div[class^='ExternalClass']").each(function(){
    str += $(this).text();
})

var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">&#160;</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow <a href="/Shared%20Documents/EBS%20Page%20Refresh%20Instructions_rkc.pdf">these instructions</a>. &#160;</div>';
$(markup).filter("div[class^='ExternalClass']").each(function(){
    console.log($(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Danmoreng
Danmoreng

Reputation: 2367

jQuerys .find() only loops through the children of the specific HTML you selected. Your variable markup has no children with the fitting class selector. The easiest way I can imagine getting this solved, is to wrap all you have in markup inside another div, and then use your jQuery selector - that works:

var markup = '<div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">Employee Self-Service pages have been corrected but may require you to refresh the page.</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">&#160;</div><div class="ExternalClass34E9F553C2F74AA2B6D693A07BA166AC">If the problem remains, follow <a href="/Shared%20Documents/EBS%20Page%20Refresh%20Instructions_rkc.pdf">these instructions</a>. &#160;</div>';
markup = '<div>' + markup + '</div>';
var str = "";
$(markup).find("div[class^='ExternalClass']").each(function(){
    str += $(this).text();
})

Upvotes: 1

Related Questions