Home > Net >  I want to add array element in class selector
I want to add array element in class selector

Time:11-11

I want to add array element in class selector, I have attached image the result is , I want div separated like this

$(document).ready(function () {
   
   var arr = ['top', 'right', "Bottom", "left"]
   var direction = "";
   $.each(arr, function (index, value) {
       direction  = value
   });
   $("#directionSec").html("<div class='directionMain'><span class='directionHeader'><h5>Header</h5>"   "<div id='result' hljs-string">">"   direction   "</div>"   "</span>");
})

enter image description here

The result I am getting

 <div class="toprightbottomleft"> toprightBottomleft</div>

The result I wanted

<div class="top">top</div> 
<div class="bottom"> bottom</div>

CodePudding user response:

You can append them this way:

var arr = ['top', 'right', "Bottom", "left"]
arr.forEach(element => {
  $('#result').append(`<div hljs-subst">${element}">${element}</div>`)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

On a side note, you have "<div id='result' >" in your example, however I'm not sure what you want to appear in the class there.

If you want a list of the array items listed as classes in the result div, like <div id="result" >, then change the append in my above example to

$('#result').append(`<div hljs-subst">${element}">${element}</div>`).addClass(element)

CodePudding user response:

This will create a string 'innerHtml' containing information about those 4 different divs with the appropriate array arr values as their class names and their text content.

Afterwards that string will be set as HTML content of #directionSec:

$(document).ready(function () {   
   var arr = ['top', 'right', "Bottom", "left"],
   innerHtml = '';
   $.each(arr, function( index, value ) {
     innerHtml  = "<div class='   value   '>'   value   '</div>"; 
   });
   $('#directionSec').html(innerHtml);
})

  • Related