Modify subset of li [duplicate]

101
December 10, 2016, at 2:44 PM

This question already has an answer here:

  • jQuery: using .text() to retrieve only text not nested in child tags 20 answers

My HTML is:

<ul id="info">
  <li>
    <span>Name:</span>Charis Spiropoulos
  </li>
  ...

and I want to change the part of the <li> that is not inside the span. How to achieve this? So far I have:

$("#info li:first").text(player);

EDIT:

I tried the solution of the suggested duplicate, with that:

$("#info li:first").clone()
            .children()
            .remove()
            .end()
            .text("foo");

and it didn't work!

Answer 1

If the text you want to replace is always the last thing in the <li>, a simple string replacement should do the trick:

var newText = "Panagiotis";
$("#info li:first").html($("#info li:first").html().replace(/[^>]+$/, "") + newText);

A quick explanation: this regular expression - /[^>]+$/ - will find all characters between the last > and the end of the text, and the replace() function simply removes them. Then you simply append the new name with +.

Answer 2

From the link provided by Andreas, you can do

$("#info li:first").clone()
            .children()
            .remove()
            .end()
            .text();

The code is pretty self explanatory, but what this does is clone the list element, remove all its children tags (in your case, the span tag), and then returns the text that is left.

Answer 3

Here's one more approach you could use:

var firstLi = $("#info li:first").get(0); //get raw DOM element;
var newContent = "Hi";
//If textContent is defined use it, otherwise use innerText:
firstLi.childNodes[2].textContent ? firstLi.childNodes[2].textContent = newContent : firstLi.childNodes[2].innerText = newContent;
Answer 4
var htmlCont  = $("#info li:first").html();
$("#info li:first").html("");
$("#info li:first").prepend(player+htmlCont);
READ ALSO
How to turn html to pdf using jspdf

How to turn html to pdf using jspdf

The demo for jspdf (http://mrriogithub

163
WCF returning syntax error via $.getJSON

WCF returning syntax error via $.getJSON

OK, so for some reason my live website is fine, but I need to publish it again with some new bits in

109