Reputation: 23
guys I need to add a class for div inside of a javascript function. I wanna put a box every agency_name
, ADRESS_TEXT
and phone
How can I do this
function jsFilt(value) {
document.getElementById("myDiv").innerHTML = "";
value.AGENCY.forEach(agency => {
$("#myDiv").append(
//HERE "<div class ="xxx" style='border-style:ridge' ><strong>Agency Name :</strong> " + agency.agency_name + "<br>" +
"<strong>Adress : </strong> " + agency.ADRESS_TEXT + "<br> "+
"<strong>Phone :</strong> " + agency.phone + "<br></div>"
);
});
}
CSS
.xxx{
width: 220px;
padding: 10px;
border: 5px solid gray;
margin: 0px;
}
Upvotes: 0
Views: 343
Reputation: 629
As others said there is two ways: .addClass('classname1 classname2')
and .attr('class','classname1 classname2')
but addClass
is better
in your case will be like:
function jsFilt(value) {
console.log('running jsFilt');
//document.getElementById("myDiv").innerHTML = "";
$('#myDiv').html(''); // this is jquery way of doing it
console.log('myDiv is now empty');
value.AGENCY.forEach(agency => {
console.log('inside loop');
//first we create that div and give it class and style
const $div = $('<div></div>').addClass('xxx').attr('style','border-style:ridge;');
// here we set innerHTML
$div.html(`
<strong>Agency Name :</strong> ` + agency.agency_name + `<br>
<strong>Adress : </strong> ` + agency.ADRESS_TEXT + `<br>
<strong>Phone :</strong> ` + agency.phone + `<br>
`);
console.log('here is the div we created:',$div);
// here we append it to the container (#myDiv)
$("#myDiv").append($div);
console.log('this is how myDiv looks like now', $("#myDiv"));
});
}
make sure you call the function of course jsFilt(someValue)
I put some console.log('bla bla')
in my codes if you open browser console you can see some messages being printed out and it helps you track issue. after everything worked you can remove console.log()
s
So this may work or may have some syntax errors. Let me know if you could get it to work
Upvotes: 1
Reputation: 66
You can addClass to the div after the append like:
function jsFilt(value) {
document.getElementById("myDiv").innerHTML = "";
value.AGENCY.forEach(agency => {
$("#myDiv").append(
"<strong>Adress : </strong> " + agency.ADRESS_TEXT + "<br> "+
"<strong>Phone :</strong> " + agency.phone + "<br></div>"
).addClass("CLASSNAME1 CLASSNAME2");
});
}
Upvotes: 0