The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript jQuery – Swapping first name and last name in list

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #26421


    I am trying to swap two spans that belong to a list. One span contains a first name, and the other contains a last name.

    I wrapped the first name and last name in their own spans, and then the entire name in a span. Here is the code.


    • FistName1 LastName1,

      FirstName2 LastName2,

      FirstName3 LastName3,

      FirstName4 lastName4.

      Paper Title (Chapter) Year. Pages.
    • ….same thing for another paper…
    • ….and again…and again…and again…lots.

    So, lots of spans. The entire thing is wrapped in a span, to accommodate for my use of tinySort, a jQuery plugin that alphabetizes the names. When citing papers, the first authors name needs to be presented as "LastName, FirstName", and then the others are "Firstname Lastname".

    So, what I am trying to do is find the first span.authorsname in each list (li) item, then swap the span.firstname with span.lastname.

    Any ideas?

    Here is the page I am working on: … techniques


    I kept plugging away at it…and came up with this solution.

    I am sure there is a better way to do this…but, this works, and I am happy with that.

    var fname = $(this).find(“.firstname”).html();
    var lname = $(this).find(“.lastname”).html();
    var name = “” + lname + “, ” + fname +”, “;

    not sure if this is a better solution, but it is more ‘dynamic’ It’s just a slight variation.

    It finds the span with a class of "authorsname" then for each it finds, it finds the "firstname", and "lastname" spans and stores the as variables (grabs the element not just the html markup of it.)

    It then removes the "firstname" span it found, and adds it after the "lastname" span, then adds the ", " separator for better formatting/readability. (so the name shows up Smith, John instead of SmithJohn.) I don;t know enough jQuery to know why that last part had to be reversed, but if you switch it you get "Lastname1Firstname1, " so I just went with what works.

    If anyone can explain that, I’d like to know…

    Anywho, this way you can change what is in the span tags (the names) and it will still work… (heck you could even change them from span tags to say div tags if needed (or in theory any other nestable elements). )

    var fname = $(this).find(“.firstname”);
    var lname = $(this).find(“.lastname”);

    $(lname).after(fname).after(‘, ‘);


    EDIT: I didn’t read that it only needed to be the first element so I updated the code now to select only the first element….

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.