1

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' class=" + direction + ">" + 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>
7
  • Can you post your html and an image of what you expect? Commented Nov 10, 2021 at 19:35
  • hi @aloisdg, I got the result but I am trying add a class in div as a element but its showing as topBottomrightleft I wanted it separately written in <div> Commented Nov 10, 2021 at 19:50
  • @radrocker Please read here: stackoverflow.com/help/minimal-reproducible-example Commented Nov 10, 2021 at 19:52
  • 1
    You mean "top right Bottom left" with spaces between the values? Commented Nov 10, 2021 at 20:02
  • hi @chazsolo, no the result is <div class="toprightbottomleft" /> i want the result div to be separated <div class="top"> <div class="right"> Commented Nov 10, 2021 at 20:07

2 Answers 2

1

You can append them this way:

var arr = ['top', 'right', "Bottom", "left"]
arr.forEach(element => {
  $('#result').append(`<div class="${element}">${element}</div>`)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>

On a side note, you have "<div id='result' class=" + direction + ">" 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" class="top right Bottom left">, then change the append in my above example to

$('#result').append(`<div class="${element}">${element}</div>`).addClass(element)
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Thanks allot for the reply @bitski

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.