christan_dk christan_dk - 3 months ago 12
CSS Question

Append div class contain spesific class using javascript

I Have one problem , I have one div with dynamic class, but i want to append in that div,which contain class name "detail-news"

Example div :

<div class="music-detail-news">
<!--- Some Content -->
</div


class name music can dynamically change, but "detail-news" still there. I try with javascript , but i dont know how to append all div class contain class name "detail-news"

Here my javascript :

function appenddiv() {
var div = document.createElement('div');
div.className = 'append_test';
document.getElementById('music-detail-news').appendChild(div);
}


how to append all div class contain class name "detail-news" , not only "music-detail-news" ?

Answer

You can use querySelectorAll with attribute class ending with the substring detail-news and then forEach over the returned NodeList to append your div element.

Check out the 2. Selectors Overview

E[foo$="bar"]

an E element whose foo attribute value ends exactly with the string bar

var detailsNews = document.querySelectorAll('div[class$="detail-news"]');

detailsNews.forEach(function(item) {
  var div = document.createElement('div');
  div.className = 'append_test';
  div.textContent = "appended div to " + item.classList;
  item.appendChild(div);
})
<div class="music-detail-news">
<!--- Some Content -->
</div>

<div class="food-detail-news">
<!--- Some Content -->
</div>

<div class="health-detail-news">
<!--- Some Content -->
</div>