1

I want to know if it's possible to add a javascript variable to html div tag just like php For example:

    $id = 1;
    <div id="test'.$id.'"></div>

<script>
var id = '1';
</script>
<div id="test..???.??"></div>
user2605321
  • 93
  • 2
  • 5
  • 11

4 Answers4

7

Not as simply as that, no. You can do something like:

<script>
  var id = '1';
</script>

and then later:

<script>
  document.writeln('<div id="' + id + '">');
</script>

...

</div>
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

You can try this

<div id="id_change"></div>    
<script>
var id = 1;
var set_id = document.getElementById("id_change").id + id;
document.getElementById("id_change").id = set_id;
</script>

Hope this answers your question

EDIT

Put the <script> code after the div else it wont find the div

zzlalani
  • 22,960
  • 16
  • 44
  • 73
0

You could use Jquery's .attr() method? Take a look here: http://api.jquery.com/attr/

http://jsfiddle.net/PxUqU/2/

var currrentID = $("div").attr("id");
var someInt = 1;
$("div").attr("id", currrentID+someInt);
Christian Bekker
  • 1,857
  • 4
  • 27
  • 43
0
var divs = document.getElementsByTagName("div"),
    newId = 1;

divs[0].setAttribute("id", newId);
OpenSorceress
  • 2,014
  • 16
  • 21