Get HTML Text That Has No Tag
I'm trying to access a piece of text inside a DIV that has no HTML through jquery (In this case the words '12 Months'). I know that I could find it if I knew the class or id, but i
Solution 1:
This works!
var a = $('.pms-subscription-plan').first().contents().filter(function() {
return this.nodeType == 3;
}).text();
console.log($.trim(a));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pms-subscription-plan">
<label>
<input type="radio" name="subscription_plans" data-price="19.99" data-duration="12" value="1219">$19.99 cada 12 meses</label>
<span class="pms-divider"> - </span><span class="pms-subscription-plan-price">19.99</span>
<span class="pms-subscription-plan-currency">$</span>
<span class="pms-divider"> / </span> 12 Months
<div class="pms-subscription-plan-description">Si usted escogió la suscripción $19.99, se le cobrará por esa cantidad anualmente.</div>
</div>
But you have to be sure that you don't restructure.
Solution 2:
var text = $(".pms-subscription-plan").contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();
Solution 3:
In this case, the following code will work:
document.getElementsByClassName("pms-divider")[1].nextSibling
HOWEVER, I would strongly recommend putting this text in a tag. This code will not work if you in any way restructure your DOM.
Solution 4:
In HTML there are elements and nodes. Each piece of text is a node. You can use the childNodes
collection.
var textNode = document.querySelector(".pms-subscription-plan").childNodes[9].data.trim();
Solution 5:
You could, as others have suggested, use the node/next sibling to get the text.
However, it would be a much better option to make a small adjustment to your html/css such as this:
<div class="pms-subscription-plan">
<label>
<input type="radio" name="subscription_plans" data-price="19.99" data-duration="12" value="1219">$19.99 cada 12 meses</label>
<span class="pms-divider"> - </span><span class="pms-subscription-plan-price">19.99</span>
<span class="pms-subscription-plan-currency">$</span>
<span class="pms-divider">/</span>
<span class="pms-duration">12 Months</span> <!--add a span class for duration--->
<div class="pms-subscription-plan-description">Si usted escogió la suscripción $19.99, se le cobrará por esa cantidad anualmente.</div>
</div>
and this small change [adding a span class for the duration] would make it easier for you in the long run. Just my tuppence!
Hope this helps
Post a Comment for "Get HTML Text That Has No Tag"