0

I would like to set the title attribute = to the inner text of a span, paragraph, or div tag using JQuery in the document.ready function.

This is my markup:

<span class="ellipsis">Text inside span tag.</span>
<p class="ellipsis">Text inside paragraph tag.</p>
<div class="ellipsis" >Text inside div tag tag.</div>

I would like to add title attributes to create markup like this:

<span class="ellipsis" title="Text inside span tag.">Text inside span tag.</span>
<p class="ellipsis" title="Text inside paragraph tag.">Text inside paragraph tag.</p>
<div class="ellipsis" title="Text inside div tag tag.">Text inside div tag tag.</div>

I understand how to change the title attribute I just can't seem to find away to change it to the specific elements value or text.

Jeremy A. West
  • 2,162
  • 4
  • 27
  • 40

2 Answers2

3

Try:

$('.ellipsis').each(function() {
  $(this).prop('title', $(this).text());
});

The .each() function is really useful in cases like this: cases in which you need something from each element individually in order to do something to the elements.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thanks Pointy, It seems so easy now that you spelled it out for me :) Worked great I will mark is as answered when my 11 minutes is up. – Jeremy A. West Jan 16 '12 at 19:49
  • I see that I had tried .hover because I did not know what function to add. I'm still pretty new to the JQuery thing. I also was trying to use .attr instead of .prop (I don't know the difference between the 2) – Jeremy A. West Jan 16 '12 at 19:52
  • Well `.prop()` was introduced with version 1.6. It makes manifest the distinction between *attributes*, which accessed on the DOM nodes via `.setAttribute()` and `.getAttribute()`, and direct *properties* of the DOM nodes. Things like "className", "id", "name", "tagName", and, of course, "title" should be accessed as properties. IE (old versions at least) don't understand what to do when you try to set a property value via `.setAttribute()`. – Pointy Jan 16 '12 at 19:58
0

Assuming that you want to set the title for each element with the ellipsis class, you can do this:

$(".ellipsis").each(function(){
    $this = $(this);
    $this.attr("title", $this.text());
});

Update

As @Pointy pointed out, in jQuery 1.6+, it's probably better to use .prop() over .attr(), even though most usages should give you same result. See .prop() vs .attr() if you want to know why.

Community
  • 1
  • 1
jrummell
  • 42,637
  • 17
  • 112
  • 171
  • 1
    It's *probably* safer to use `.prop()` instead of `.attr()` in jQuery versions since 1.6, particularly in older versions of IE. – Pointy Jan 16 '12 at 19:50