user3495224
user3495224

Reputation: 49

Show the corresponding text of each attribute

need to show the text that is in the title attribute, made ​​an attempt however shows only the first text, I would like the text that appears each ID.

jQuery

var nombreItemText = $('#questionsForm .title').attr("title");
$("#questionsForm .title #question-count").text(nombreItemText);

JSFIDDLE

Upvotes: 0

Views: 51

Answers (3)

George
George

Reputation: 36784

You need to loop through each element and change the text for each context.

Currently you are getting the title attribute of the first element returned from the selection and setting the HTML for all <span>s to that value.

You can pass a function to the text() method and within that function the context is the current <span>, so you can target the parent <h2>s title attribute with parent() or closest():

$(".container .title span").text(function(){
   return $(this).closest('h2').attr('title'); 
});

JSFiddle

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101614

When multiple elements are involved, you need to use .each:

// iterate over each .title element
$(".container .title").each(function(){
    var $this = $(this); // reference to .title element
    // find the nested span element
    $this.find('span')
        // and place the .title's title within
        .text($this.prop('title'));
});

http://jsfiddle.net/TW4Ch/2/

Also, you should be using .prop, but you'd have to know that HTMLElement.title exists.

Upvotes: 0

Sharikov Vladislav
Sharikov Vladislav

Reputation: 7269

Use .each() function.

$('#questionsForm .title').each(function () {
    var nombreItemText = $(this).attr("title");
    $('span', $(this)).text(nombreItemText);
});

DEMO

Upvotes: 1

Related Questions