Craig Shearer
Craig Shearer

Reputation: 14521

Updating text node using jquery

I have this html:

<span class="msg-container">
  <span class="msg"></span>
  A message here
</span>

I'm wanting to use jQuery to find all the msg-container elements, take the "A message here" text and set the title attribute and remove the "A message here" text node.

So, after executing, my DOM should look like this:

<span class="msg-container" title="A message here">
  <span class="msg"></span>
</span>

How do I achieve this?

Upvotes: 0

Views: 58

Answers (3)

COLD TOLD
COLD TOLD

Reputation: 13579

I think you need to use for-each function

 $(".msg-container").each(function(){
       var child =  $(this).children(".msg").html();
       var text=$(this).html("");
        $(this)attr("title" , text) 
        $(this).append(child);
      });

Upvotes: 1

Jaime
Jaime

Reputation: 6814

Try

$(function()  {
    $(".msg-container").each(function() {
        var txt = $(this).text();
        var children = $(this).children();
        $(this).attr("title",txt.trim())
            .text("").append(children);
    });
});

Upvotes: 1

Fresheyeball
Fresheyeball

Reputation: 30015

 $('.msg-container').each(function(){
      var that = $(this);
      that.attr('title', that.text());
      var children = that.find('.msg').clone();
      that.html('').append(children);
 });

Upvotes: 1

Related Questions