Hitesh
Hitesh

Reputation: 1

ID replace and new ID use for further process in Jquery

On "click" I am changing ID of myDiv to myDiv1. Now I want to use new ID (myDiv1) which replaced myDiv.

$("#myDiv").attr('id', 'myDiv1');

but I can't further manipulation with myDiv1 like:

$("#myDiv1").mouseover(function() {
    $('#bottom_link').show(400);
});

Upvotes: 0

Views: 74

Answers (4)

totallyNotLizards
totallyNotLizards

Reputation: 8569

A better way (IMO) to do this would be:

var myDiv = $("#myDiv");

This caches the div as a jQuery object, so you can manipulate it all you like and still be able to do things with it without having to select it again.

Eg:

myDiv.attr("id", "someOtherId");
myDiv.css("background-color", "orange");

Fiddle: http://jsfiddle.net/DWeSL/

Edit:

You can then also bind events to this like:

myDiv.click(function(){
  alert("boo");
});

Upvotes: 2

jbabey
jbabey

Reputation: 46647

Not that I agree with changing IDs dynamically, but your problem may be that you are trying to attach event handlers to the element before it exists under the new ID. Try using jQuery's delegate to attach the event instead.

Edit: adding some code as $.delegate is not the friendliest function to learn...

$.delegate('#myDiv1', 'mouseover', function() {
    $('#bottom_link').show(400);
});

This will ensure that any element with the ID "myDiv1" that exists now or any time in the future will have this event handler bound to it.

Upvotes: 1

Caleb Gray
Caleb Gray

Reputation: 3097

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
$(function(){
  $("#myDiv").text('Test1');
  $("#myDiv").attr('id', 'myDiv1');
  $("#myDiv1").text('Test2');
});
</script>
</head>
<body>
<div id="myDiv">Test</div>
</body>
</html>

Upvotes: 0

Gjohn
Gjohn

Reputation: 1281

Instead of selecting your div by its id select it by classname. You would do

<div = "myDiv" class="myDiv"></div>

$(".myDiv").mouseover(function() {
......your code here.......
});

Upvotes: 0

Related Questions