2

I need to target a single instance of a class, using JQuery, because I need to insert a new chunck of html code after (or before) an element on the page. My first thought was to use the "inserAfter" method. But, I soon realized it was a common class used several times in the document. The default syntax is like this, I believe:

$('<p>Test</p>').insertAfter('.inner');

I read that you can use siblings method, but I dont' see how I can combine the insertAfter/Before, and also, the instances of the class are identical - from body down to the actual content. So it's about targeting the second instance out of 5 (instances) or something and insert bla, bla code.

Is it possible? Or should I re-think the whole plan and... do something else? Thanks for any ideas, hints or suggestions.

2 Answers 2

1

You can use eq() to target a specific instance of a class based on index. As it starts at zero, eq(1) would be the second instance of the class .inner :

$('.inner').eq(1).after('<p>Test</p>');
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

$('.inner:nth-of-type(2)').after('<p>Test</p>');

Source(s)

jQuery API - nth-of-type() Selector

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.