Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the id of a parent div using Jquery

I have some html like this:

<div id="1">     <p>         Volume = <input type="text" />         <button rel="3.93e-6" class="1" type="button">Check answer</button>     </p>     <div></div> </div> 

and some JS like this:

$("button").click(function () {     var buttonNo = $(this).attr('class');     var correct = Number($(this).attr('rel'));      validate (Number($("#"+buttonNo+" input").val()),correct);     $("#"+buttonNo+" div").html(feedback); }); 

What I'd really like is if I didn't have to have the class="1" on the button (I know numeric classes aren't valid, but this is a WIP!), so I could determine buttonNo based on the id of the parent div. In real life there are multiple sections looking like this.

  1. How do I find the id of the div parenting the button.

  2. What would be a more semantic way to store the answer in the button code. I want to make this as foolproof as possible for a non programmer to copy and paste without breaking things!

like image 819
Rich Bradshaw Avatar asked Feb 13 '09 13:02

Rich Bradshaw


People also ask

How can I get the ID of an element using jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I find a specific parent in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

How can get parent div id on button click?

parent() so $(this). parent() but this would get the parent div of the input.


1 Answers

You could use event delegation on the parent div. Or use the closest method to find the parent of the button.

The easiest of the two is probably the closest.

var id = $("button").closest("div").prop("id"); 
like image 108
Mark Avatar answered Oct 11 '22 22:10

Mark