Well I am learning javascript and I am trying to write a function which would look if(href.contains(1234567)
and change class="price"
value to any number.
I tried googling but I cant seem to find an answer to this
<div class="product-info">
<a href="https:someUrl.com/1234567">
<div class="title">
Some Sweet Title
</div>
</a>
<div class="price">
ValueHereNeedsToBeAdded
</div>
</div>
I expect class="price"
value to be changed to some number
You can use the a[href*=1234567]+.price
selector to do it.
a[href*=1234567]
select all <a>
elements that have a href attribute value containing "1234567" and +.price
select element has class price placed immediately after that a[href*=1234567]
.
Demo:
$('a[href*=1234567]+.price').text(123456)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="product-info"> <a href="https:someUrl.com/1234567"> <div class="title"> Some Sweet Title </div></a> <div class="price"> ValueHereNeedsToBeAdded </div> </div> <a href="https:someUrl.com/test"> </a> <div class="price"> ValueNoNeedsToBeAddedHere </div>
You can do without jquery :-
<div class="product-info">
<a href="https:someUrl.com/1234567" id="link_id" onclick="check(this.href)">
<div class="title">
Some Sweet Title
</div></a>
<div class="price" id="setvalue">
ValueHereNeedsToBeAdded
</div>
</div>
function check()
{
event.preventDefault();
var href = document.getElementById("link_id").getAttribute("href");
if(href.includes(1234567))
{
document.getElementById('setvalue').innerHTML = '1313133';
}
}
A solution with jQuery:
function myFunction() { var str = $('#link').attr('href'); if (str.indexOf("1234567") >= 0){ var x = document.getElementsByClassName("price"); var y = x[0]; y.classList.add('myClass'); y.classList.remove('price'); y.innerHTML = "123456" } } myFunction();
.myClass{ background: yellow; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="product-info"> <a id="link" href="https:someUrl.com/1234567"> <div class="title"> Some Sweet Title </div> </a> <div class="price"> ValueHereNeedsToBeAdded </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.