Javascript: select n-th child? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Javascript: select n-th child?

Hi everyone. I'm new to all of this, sorry if my question is silly. I wanted to write a code that lets the user add paragraphs and edit them, and there is a counter that associates ordered IDs to the paragraphs so that the user can select the number of the paragraph he wants to edit. The problem with this code is that removing one paragraph translates into a bug since the IDs are not ordered anymore. For example, if there are 5 paragraphs: <p id="new1"></p> <p id="new2"></p> <p id="new3"></p> <p id="new4"></p> <p id="new5"></p> and the user delets the second: <p id="new1"></p> <p id="new3"></p> <p id="new4"></p> <p id="new5"></p> he will try to select the second paragraph displayed, but as he gives the number "2" as an input there will be an error since no "new2" will be found. Or, if he tries to select the third paragraph displayed by giving the input "3", the script will actually manipulate the second displayed (ID: new3). Now, I wonder if there is anything like "remove nth-child", something that doesn't rely on IDs to manipulate the HTML code. P.S. Mind that I still haven't finished the JS course, idk if that makes any difference. P.P.S. Sorry for my English :)

28th Jul 2018, 12:53 PM
asdfg
asdfg - avatar
6 Answers
+ 5
document.getElementsByTagName("p") returns an array of all p elements in the document. You can use it to access p elements by order.
28th Jul 2018, 12:57 PM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 6
@JonathanP Thank you, I didn't know that! Edit: what if I don't want to access all the p elements, just those with a specific parent? @Roel Nope, but you gave me an idea! Thanks
28th Jul 2018, 1:01 PM
asdfg
asdfg - avatar
+ 5
@JonathanP @Calviղ Thanks to both for your precious input :)
28th Jul 2018, 2:00 PM
asdfg
asdfg - avatar
+ 2
Sorry for my English too, but is your question 'i want to select the one he clicked on?' because in that case you could use the 'this' keyword P.S. can you show a code or a link to one
28th Jul 2018, 12:58 PM
Roel
Roel - avatar
+ 2
You can use the children property. It returns an array of all children elements of the specified parent. Here's a reference: https://www.w3schools.com/jsref/prop_element_children.asp
28th Jul 2018, 1:48 PM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 2
Francesca You should use querySelector and querySelectorAll to target specific parent child elements. Check out this sample: touch paragraph to delete, add extra paragraph from input text with enter https://code.sololearn.com/W243Cdb9XgWo/?ref=app
28th Jul 2018, 1:49 PM
Calviղ
Calviղ - avatar