1

I wanted to put an id in my element's parent element. Below is my code:

<div>
    <div id="child"></div>
<div>

Im aware that jquery has a way to select a parent element , but I dont know how what method shall I use to put an id to it. Below is my jquery code:

div_resizable = $( "#child" ).parent();
div_resizable.id = "div_resizable";

Above code doesnt work with me. It doesnt throw an error, but no changes had taken effect. Any solution to my problem?

  • try `div_resizable.attr("id", "div_resizable");` – VPK Feb 24 '15 at 01:19
  • A friendly tip, next time you have an issue, before you ask a question here, use [`console.log`](https://developer.mozilla.org/en-US/docs/Web/API/Console/log)s or [`debugger`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger) statements to determine what each variable's value is. – Sumner Evans Feb 24 '15 at 01:22

3 Answers3

2

For achieve what you want, you can use the jquery attr:

$("#child" ).parent().attr('id', 'newID');

Or you can use the prop:

$("#child" ).parent().prop('id', 'newID');

And you can check the difference between the two here: difference between prop() and attr()

Community
  • 1
  • 1
2

Of course div_resizable.id = "div_resizable" doesn't work. div_resizeable is an jQuery array and you are trying to assign id to it.

Try .attr instead:

$("#child").parent().attr({id: "div_resizable"});
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

To set a property on the first element inside a jQuery result object:

div_resizable = $( "#child" ).parent()[0];
//                                    ^^^
div_resizable.id = "div_resizable";

This picks the first Element from the result so that you can directly access the property.

Or:

$('#child').parent().prop('id', 'div_resizable');

Use the .prop() helper method to accomplish the same thing.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309