Himmators
Himmators

Reputation: 15006

Insert value of attribute before each element in the set of elements with jquery?

I would like to use jquery to convert

<div data-expand-label="foo" />
<div data-expand-label="bar" />

into

<p>foo</p>
<div data-expand-label="foo" />
<p>bar</p>
<div data-expand-label="bar" />

This is what I thought would work:

$('[data-expand-label]').before('<p>'+$(this).attr('[data-expand-label]')+'</p>');

but 'this' doesn't seem to work. Why? and what should I do instead?

Upvotes: 0

Views: 55

Answers (3)

John Dvorak
John Dvorak

Reputation: 27287

this is only evaluated once (per entering the code in question), so it can't be both <div...foo> and <div...bar>. You will need to iterate over the elements.

.before accepts a callback argument, which will happily iterate for you. You do, however, need to supply a callback. Change:

$('[data-expand-label]').before(
  '<p>'+$(this).attr('[data-expand-label]')+'</p>'
);

(your code) to:

$('[data-expand-label]').before(function(){
  return '<p>'+$(this).attr('[data-expand-label]')+'</p>'
});

or, better yet, if data-expand-label is supposed to be a text,

$('[data-expand-label]').before(function(){
  return $('<p>').text($(this).attr('[data-expand-label]'))
});

Upvotes: 0

Derek
Derek

Reputation: 4751

You need to iterate over each element you want to apply the new element to, like so:

$('div[data-expand-label]').each(function() {
    $(this).before($('<p></p>').html($(this).attr('data-expand-label')));
});

Upvotes: 0

Terence Jefferies
Terence Jefferies

Reputation: 358

I think it might be easier to try the following:

$(document).ready(function() {
    $('[data-expand-label]').each(function() { $(this).before('<p>'+$(this).attr('data-expand-label')+'</p>'); });
});

I don't believe you can use "$(this)" in the context in which you were, it needs to be referenced in the above manner.

Hope this has helped.

Upvotes: 1

Related Questions