Javascript: select n-th child? | Sololearn: Learn to code for FREE!


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 :)

7/28/2018 12:53:35 PM


6 Answers

New Answer


document.getElementsByTagName("p") returns an array of all p elements in the document. You can use it to access p elements by order.


@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


@JonathanP @Calviղ Thanks to both for your precious input :)


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


You can use the children property. It returns an array of all children elements of the specified parent. Here's a reference:


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