privateer35 privateer35 - 1 year ago 67
Javascript Question

Take text node of an element and manipulate it with Javascript

I have a set of elements that contain prices as such:

<em class="price">$859</em>
<em class="price">$159</em>
<em class="price">$850</em>
<em class="price">$350</em>
<em class="price">$560</em>
<em class="price">$200</em>
<em class="price">$250</em>
<em class="price">$900</em>

How would I be able to grab the values within the
tags and

I know I can perform
to grab the first one, and just change the value of the index in
to grab any other one I wish.

Is there a way to take all the text node values at once without the use of a loop?

The bigger picture for why I would want to do this is I need to take each number in a
tag multiply it by a percentage, take that computed value and insert it into a newly generated element.

Is there a way to say (sudo code) "take all instances of
tags with the class
, multiply the text inside by
, and then insert newly computed values into
tags with the class called

This is how I'm using it currently:

$(document).ready(function() {

function setCheckPrice(){

var productPrice = document.getElementsByClassName('p-price');





This isn't logging anything in the console.

Using jQuery for when the document loads to apply the needed Javascript.

Answer Source

Using a loop is probably best for what you want to do and to use jQuery as you already have it loaded. Try this:

function setCheckPrice() {
  $('.price').each(function(key, val) {
    var price = $(val).html().replace('$', '');
    var newPrice = parseInt(price) * 10;
    $(val).after('<em class="new-price">$' + newPrice + '</em>');


This will take each price, multiple it by 10 and insert it into a new em after the original one.

To target a single price, you'll just need to remove the each loop, for example:

function setCheckPrice() {
  var element = $('.price:nth-of-type(5)');
  var price = $(element).html().replace('$', '');
  var newPrice = parseInt(price) * 10;
  $(element).after('<em class="new-price">$' + newPrice + '</em>');


You can target other elements by changing the 5.