Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Change text in a div if another div has a specific attribute

I would like to change a text in a div if another div has a specific attribute, in my case data-value.

In the specific if a div has an attribute data-value="cars" another div should have the text "Buy".

In the specific if data-value="cars" I would like to change the text "1" into "Buy"

<div class="one">1</div>

Here the sample code

<div class="dynamic">
  <div class="content">
   <div data-value="cars">
   Cars
   </div>
   <div data-value="truck">
   Truck
   </div>
   <div data-value="moto">
   Moto
   </div>
 </div>
</div>



<div class="change">
 <div>
 1
 </div>
 <div>
 2
 </div>
</div>

How can I achieve that in JS?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you need to first perform a query on the existence of any element within the content having the data-value attribute of "cars"

use the document.querySelector() function

  if (document.querySelector('.dynamic .content [data-value="cars"]')) ...

then you need to set the text content of all the div elements within the change that have the value 1, using the .textContent attribute

document.querySelectorAll('.change div')
  .forEach(div => if( div.textContent=="1") div.textContent="Buy");

putting all pieces together

  if (document.querySelector('.dynamic .content [data-value="cars"]')) {
  document.querySelectorAll('.change div')
    .forEach(div => if(div.textContent=="1") div.textContent="Buy" );
  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!