简体   繁体   English

仅当它在父div中时才使用innerHTML选择类

[英]use innerHTML to select class only if it is in a parent div

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"? 我将如何调整它,使其仅在父标记为“#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. 您可以使用parentElement属性获取元素的父元素。 Then just check its id. 然后只需检查其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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM