i currently have the code below which searches for the class and will replace the text.
how would i tweak it so it only will replace text if the parent tag is "#thumb-hockey-top"?
window.onload = function(){
//this captures all the elements with the spec classes
var soldItems = document.getElementsByClassName('product-mark sold-out');
//this changes each element 1 by 1 to new text
for(var i=0; i<soldItems.length; i++){
soldItems[i].innerHTML = "Coming Soon";
}
}
window.onload = function(){ //this captures all the elements with the spec classes //just use a class var soldItems = document.getElementsByClassName('sold-out'); //this changes each element 1 by 1 to new text //var parentnode = document.getElementById('thumb-hockey-top') for(var i=0; i<soldItems.length; i++){ if(soldItems[i].parentNode.id=='thumb-hockey-top'){ soldItems[i].innerHTML = "Coming Soon"; } } };
<div id="thumb-hockey-top"> <div class="product-mark sold-out"></div> <div class="product-mark sold-out"></div> <div class="product-mark sold-out"></div> </div>
You can get the parent element of an element using the parentElement attribute. Then just check its id.
var soldItem = soldItems[i];
if (soldItem.parentElement.id == "thumb-hockey-top") {
// do your thing
}
Use once
window.onload = function(){ //this captures all the elements with the spec classes var soldItems = document.getElementById("thumb-hockey-top").getElementsByClassName('product-mark sold-out'); //this changes each element 1 by 1 to new text for(var i=0; i<soldItems.length; i++){ soldItems[i].innerHTML = "Coming Soon" } }
<div id="thumb-hockey-top"> <div class="product-mark sold-out"></div> </div> <div class="product-mark sold-out"></div> <div class="product-mark sold-out"></div>
Use multiple times
function myF(a, b){ // a = Id of parent element // b = Class Name of element which you want to hack var soldItems = document.getElementById(a).getElementsByClassName(b); for(var i=0; i<soldItems.length; i++){ soldItems[i].innerHTML = "Coming Soon" } } myF("thumb-hockey-top", "product-mark sold-out"); myF("thumb-hockey-bottom", "product-unmark sold-out");
<div class="example1"> <div id="thumb-hockey-top"> <div class="product-mark sold-out">EXAMPLE 1</div> </div> <div class="product-mark sold-out">EXAMPLE 1</div> </div> <div class="example2"> <div id="thumb-hockey-bottom"> <div class="product-unmark sold-out">EXAMPLE 2</div> </div> <div class="product-unmark sold-out">EXAMPLE 2</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.