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>
6
  • 2
    what exactly are you trying to do here? Is that all the code that you have ? Commented Jul 22, 2013 at 17:07
  • {$id} needs <?php ?> tags Commented Jul 22, 2013 at 17:08
  • i edited.. check..just want to get the javascript variable and insert into the div tag. Commented Jul 22, 2013 at 17:08
  • You are possible asking this? stackoverflow.com/questions/2801729/… Commented Jul 22, 2013 at 17:08
  • I think this is closely related to what you're asking, and unfortunately the answer is no....you can't use javascript variables in-line like that. stackoverflow.com/questions/3304014/… Commented Jul 22, 2013 at 17:09

4 Answers 4

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>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0
var divs = document.getElementsByTagName("div"),
    newId = 1;

divs[0].setAttribute("id", newId);

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.