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?
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" );
}