-3

I have a full name in a class .label-name that has multiple instances.

<span class="label-name">Joe Demo</span>
<span class="label-name">Jane Demo</span>
<span class="label-name">Lisa Demo</span>

How can I replace the the full name with only the fist name?

Chozen
  • 299
  • 1
  • 4
  • 18
  • 2
    this is a simple issue with a simple solution. a quick google search will provide any information you need. It's my opinion that this question needs to be closed as a duplicate – Brett Weber Jul 19 '14 at 19:47
  • Apparently there is such a thing as a stupid question, I guess that's what I was doing. I thought if I don't know how to do something and I couldn't find it, I should ask. Guess not. – Chozen Jul 20 '14 at 03:10

1 Answers1

1

You may get the text, split it by spaces, and take the first element.

For example:

$( document ).ready(function() {
    var fullName = $(".label-name").first().text(); //This will get the text from the first element with the class label-name
    var nameArray = fullName.split(" "); //Split the text by spaces into an array
    var firstName = nameArray[0]; //Take the first element of the array 
    $(".label-name").first().text(firstName); //Set the text of the first element with the class label-name to the first name
});

EDIT: As I noted in the comments, this will get the first element with the class label-name. If there are multiple elements with this class you may need a different selector. The jQuery selectors are documented at http://api.jquery.com/category/selectors/. If you post the full HTML source and let me know which element you want I will offer further advice.

EDIT 2: If you need to select and replace in multiple elements with the same class, you can drop the .first() selector from the code and use a loop to edit the results. For example:

$( document ).ready(function() {
    var fullNameObjects = $(".label-name");
    $.each(fullNameObjects, function () {
         var nameArray = this.split(" ");
         var firstName = nameArray[0];
         this.text(firstName);
    });
});
Justin Russell
  • 488
  • 2
  • 10