Skip to content Skip to sidebar Skip to footer

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() {
    returnthis.nodeType == 3;
}).text();

console.log($.trim(a));
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="pms-subscription-plan"><label><inputtype="radio"name="subscription_plans"data-price="19.99"data-duration="12"value="1219">$19.99 cada 12 meses</label><spanclass="pms-divider"> - </span><spanclass="pms-subscription-plan-price">19.99</span><spanclass="pms-subscription-plan-currency">$</span><spanclass="pms-divider"> / </span> 12 Months
  <divclass="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() {
    returnthis.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><inputtype="radio"name="subscription_plans"data-price="19.99"data-duration="12"value="1219">$19.99 cada 12 meses</label><spanclass="pms-divider"> - </span><spanclass="pms-subscription-plan-price">19.99</span><spanclass="pms-subscription-plan-currency">$</span><spanclass="pms-divider">/</span><spanclass="pms-duration">12 Months</span><!--add a span class for duration---><divclass="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"