Problem is when you use text() it will return the first item in the collection. It has no clue you want to grab it for other elements. So you need to code it to deal with the relationships.
You will have to loop over each group and select each one in the group.
$(".main").each( function () {
var elem = $(this)
var text = elem.find(".second").text()
elem.find(".first").text(text)
})
The problem is because your code selects all .first elements.
To fix the problem you can select the second div in each .main block and provide a function to text() which returns the text of the previous sibling. Try this:
I want to change B text with A text and D text with C text with jquery. I added this script:
$('.second').html($('.first').html());
but it change A text in both main div
Comments
Comment posted by epascarello
So you will have to loop over the main elements and select them
Comment posted by chriskirknielsen
Your code is looking for any first result for
Comment posted by nasir
Thank you Rory,its working, can you please do it without selector.
Comment posted by Rory McCrossan
So in this case which text should be overwritten? I’d suggest updating the question with a more accurate example of the HTML
Comment posted by nasir
can you do it with only class name
Comment posted by Rory McCrossan
Probably, but you haven’t shown what the class names are for the other divs. @epascarello’s answer shows solutions which may work for that case. You should note that the better approach, IMO, would be to do it using ordinal position in the container, though.