magento two magento two - 1 month ago 5
Ajax Question

How to get a div text from html content

Hi I am trying to get the div data from another html page. For these I am get the html data through

$.ajax({});
it's returned bunch of html content from this I am trying to get div text but it's returning empty.

My Code is:

$(document).ready(function() {

$.ajax({
url:'/Myrewards.asp',
type:'GET',
success: function(data) {
var result = $(data).filter("#content_area").html();
var result_1 = $(data).filter("#rewards_point_display").text();
console.log(result);
}
});
});


result
is returned below html code.

<form action="" method="post">
<div id="div_articleid_141">
<link type="text/css" rel="stylesheet" href="/a/c/myrewards.css"> <div id="rewards_content"> <h3>MyRewards - Reap the rewards with every purchase</h3> It pays to go with MyRewards. Every time you make a purchase with [your company or website's name], you'll receive points [if product based, then] for the product(s) you purchase [if total amount of purchase, then] based on your total purchase amount. It's a great way to save on your next purchase whether it's for you or someone special. <h4>Here's how it works:</h4> <ol> <li>Once you've placed your order and it has shipped, your MyRewards Point will be redeemable in [X] days.</li> <li>To view your MyRewards, simply go to <a href="/MyRewards.asp">MyRewards</a>.</li>
<li>Enter the total amount (in points) you'd like to redeem below (X points = $X).</li> <li>You're now ready to save on your next purchase. Upon placing your order, your available MyRewards will automatically be deducted from the total purchase amount.</li>
</ol> <div id="rewards_point_display"> Available Points: 100<br> Pending Points: 0 </div> <input id="points_to_redeem" name="points_to_redeem" value="100" type="text">
<input id="redeem_now_button" src="/v/vspfiles/templates/253/images/Buttons/btn_redeem.gif" value="Redeem" name="go" alt="Redeem" type="image">
<div id="rewards_terms">Want to learn more about MyRewards? For more MyRewards information, see the <a href="articles.asp?ID=140">Terms &amp; Conditions</a>.</div>
</div></div>

</form>


from above text I am trying to get
rewards_point_display
div text, but it's not working.

Any help?

Thanks

Answer

IMO, you should use jQuery.parseHTML()

Parses a string into an array of DOM nodes.

var bad = $.parseHTML(result);

OR

Use .filter()

console.log($(result).filter('#rewards_point_display').html());

Reference

var result = "<div>First Div</div><div id='rewards_point_display'>Text of rewards_point_display</div>";

//Use filter
console.log($(result).filter('#rewards_point_display').html());


//use parseHTML
var data = $.parseHTML(result);
$(data).each(function() {
    console.log($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments