1

how can change the value of the first price span using javascript

<span class="regular-price" id="product-price-27">
    <span class="price">$2,699.99</span>  
</span>


<span class="price">$2,000</span>

i've tried with getElementByClassName but it change for the tow of them

i want just to change the value of the first one <span class="price">$2,699.99</span>

7 Answers 7

1

Check this demo jsFiddle

getElementsByClassName("price") - Get all element, whose class name price

[0] - Its take first element of price class.

JavaScript

 var newprice = document.getElementsByClassName("price")[0].innerHTML = "$3,000.00";    // Assign New Value $3,000.00

HTML

<span class="regular-price" id="product-price-27">
    <span class="price">$2,699.99</span>  
</span>
<br />

<span class="price">$2,000</span>    
Sign up to request clarification or add additional context in comments.

Comments

0

Try this, which first gets the outer span element, then all the elements within it with that class...

 var outerSpan = document.getElementById("product-price-27");
 var innerSpans = outerSpan.getElementsByClassName("price");
 innerSpans[0].innerHTML = "$xxxx";

Here is a live JSFiddle demo

Comments

0

then use getElementsByClassName("price")[0] it will work for the first element only

Comments

0
$( ".price" ).first().text( "your text" );

Please take a look at this .first

using javascript

var parentElement = document.getElementsByClassName("price")[0]
parentElement.innerText="your price"

4 Comments

OP doesn't mention jquery
Well, it would be OK if it worked, but ".price" isn't going to find it
why? it would not be?
.price is a jquery format for finding class="price", in the same way #price would find id="price". Doesn't work like that for vanilla JS
0

Try getElementById("product-price-27")

Comments

0

If is the first element with the class price on your code:

var myelement=document.getElementsByClassName('price')[0];
myelement.innerHTML='new content';

If you are not sure if it will be the first BUT you know the actual value, you could:

var actualValue='whatever';
var elements=document.getElementsByClassName('price');
for (var i in elements){
    if (elements[i].innerHTML==actualValue)
    {
        elements[i].innerHTML=newValue;
        break;
    }
}

Comments

0

Here It is, check the

var x = document.getElementsByClassName("price");
 x[0].innerHTML = "$2000";


http://jsfiddle.net/kushalraid/mjVH8/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.