0

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?

3 Answers 3

1
 $('.msg-container').each(function(){
      var that = $(this);
      that.attr('title', that.text());
      var children = that.find('.msg').clone();
      that.html('').append(children);
 });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that's pretty much what I want :)
1

Try

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

1 Comment

.text(''); will wipe out the child span.msg along with anything else in the container
1

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);
      });

1 Comment

This does not remove the text node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.