简体   繁体   中英

How to use javascript to add classes to text and image

I would really appreciate help with running a query for.parentContainer, then find text ABC123 and wrap this in a div with ID="abc123". I already have some simple code that will add content to the new div element.

Further to that, is it possible to also query.parentContainer for the presence of ABC123, and then add a new class to the image if ABC123 exists?

Sorry if I appear a bit lazy here. I have really only started dabbling with JavaScript and have been reading lots on manipulation of the DOM. I tend to learn loads from studying and tweaking code that can apply to my own real scenarios.

Thanks so much!

 let parentContainers = document.querySelectorAll('.parentContainer') for(let [i,f] of parentContainers.entries()){ if(f.innerText.includes('ABC123')){ let div = document.createElement('div'); div.innerText = 'ABC123'; div.setAttribute("id", "abc123"); f.append(div) } }
 #ABC123 { border: 3px solid red; } #abc123 { border: 3px solid green; }.abc123 { border: 2px solid purple; }.parentContainer { padding: 10px; border: 2px solid black; margin: 10px 0; }
 <div class="parentContainer"> <a class="productImage" href="https://www.mywebsite.com/product-1"><img src="https://via.placeholder.com/350x150" alt="Product 1 Image"></a> <div class="productInfo"> ABC123 Product summary description goes here. </div> </div> <div class="parentContainer"> <a class="productImage" href="https://www.mywebsite.com/product-1"><img src="https://via.placeholder.com/350x150" alt="Product 1 Image"></a> <div class="productInfo"> ABC123 Product summary description goes here. </div> </div>

Try this out

let parentContainers = document.querySelectorAll('.parentContainer')
  for(let [i,f] of parentContainers.entries()){
    if(f.innerText.includes('ABC123')){
    let div = document.createElement('div');
    div.innerText = 'ABC123';
    div.setAttribute("id", "abc123");
    f.append(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.

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