0

i have something like this :

<li id="test">
    <input type="text" name="firstname" />

</li>

<li id="test2">
    <div id="special">
        <input type="text" name="city" />
        <input type="text" name="pc" />
   </div>
</li>

When a user clicks on one input, I'd like to get all lis with an input child. For example, if a user clicks on .pc, I'd like to return both #test and #test2. I cannot use jQuery or any other external libraries.

astex
  • 1,045
  • 10
  • 28
deveLost
  • 1,151
  • 2
  • 20
  • 47
  • Do you mean that you want to get the closest 'li' parent? – astex Apr 30 '14 at 19:20
  • yes, i want to get all of 'li' parent of each input – deveLost Apr 30 '14 at 19:31
  • Okay, so you want every `li` with an `input` child whenever a user clicks on an `input`? – astex Apr 30 '14 at 20:01
  • yes, but only in javascript if it's possible. – deveLost May 01 '14 at 11:41
  • Generally speaking, if you want to do something a library can do without using the library, it's a good idea to look at the library's source (here's jQuery's: https://github.com/jquery/jquery). I'll go through and try to parse that into a useful answer. – astex May 01 '14 at 12:00

2 Answers2

0

for the second one (test2 in pc), you could use

$('#pc').closest('li');

to grab the closest parent of type li. (this would return just test2)

If you want both, however, you could give them a unique class (or something to help pick them out), and you could use

$('#pc').parents('li.myclass');

as an example

Edit: these are assuming also that you only want these two tests. If you want all of the li's, you could just use

$('#pc').parents('li');

Edit2: If it is not possible to use JQuery, there is a method someone wrote to handle this here

Community
  • 1
  • 1
Dylan Corriveau
  • 2,561
  • 4
  • 29
  • 36
  • 1
    OP didn't say he can use jQuery, and didn't add the tag. Try not using jQuery in answers then. – Joeytje50 Apr 30 '14 at 19:27
  • ok thx, i will try it, and indeed, i don't want to use jQUery. – deveLost Apr 30 '14 at 19:31
  • ok, yea try the second edit then. I should have checked first if you were comfortable with using JQuery haha. – Dylan Corriveau Apr 30 '14 at 19:36
  • $('#pc') wouldn't even select anything the OP provided. The selector for that element would need to be $('input[name="pc"]'), and then this isn't returning what the OP asked for, all lis with an input as a child. – Scottux May 01 '14 at 12:33
0

There is a reason jQuery is around...

You could start with looping over document.getElementsByTagName('li') then loop through the children, looking for an element with a tagName === 'INPUT' and then loop through the children's children etc.

Or go the other way checking parent from all inputs as in this answer -> How to check in Javascript if one element is contained within another

Community
  • 1
  • 1
Scottux
  • 1,577
  • 1
  • 11
  • 22