Reputation: 10581
Is it possible to assign a class from a php variable to a new appended div in jquery?
$newItems = $('<div class="PHP VARIABLE PRINTS HERE A CLASS"></div>');
In my case, for other things, I am defining a var to defign what I then append in jquery but I need to get the class of the newly inserted div from a php variable. Is it possible?
Upvotes: 1
Views: 835
Reputation: 191789
I think that hardcore mixing of PHP and JavaScript code is an anti-pattern and can lead to confusion. I would limit PHP emissions to build HTML and use the JavaScript code to parse said HTML to get your desired client result:
//php
echo '<span hidden id=class-container data-class=name_of_my_class>';
//JavaScript
$("<div>").addClass($("#class-container").data('class'));
Upvotes: 0
Reputation: 50
There are two different ways I would imagine doing this.
Firstly you could use Ajax to get the variable earlier on, from the php variable, or you could simply echo the variable there inline from a function within the file.
The first way of doing this, using Ajax, is perhaps a more standard way of doing this, whereas I would count the latter method as a little bit quick and dirty.
Upvotes: 1
Reputation: 706
In PHP
<?php
// First you need to have the variable with the name of classe
$myClass = 'name_of_my_classe';
?>
In Javascript:
$newItems = $('<div class="<?php echo $myClass; ?>"></div>');
Upvotes: 4