crankshaft
crankshaft

Reputation: 2677

jquery refer to initial element selector in following selectors

Is it possible to refer to the original selected element in the following select statement something like this:

$('.someclass').next('span').hide().parent().append('<input class="textbox" name="'+$(this).attr("name")+'-x'+'"/>');

Where $(this) was the original $('.someclass') element.

I am trying to get attributes from the inital element to apply to another element in the statement.

edit

Since the initial element is selected by class, there are multiple elements with the same classname.

This is the source html:

<div>
<input class="someclass" name="somename">
<span></span>

I want to hide the input, and add a new input using the original input's name with a prefix.

Upvotes: 2

Views: 52

Answers (2)

Popnoodles
Popnoodles

Reputation: 28409

Your title asks something different to your question.

.end() traverses to the initial element, but you want to use that element to affect another.

$('.someclass').each(function(){
    $(this).next('span').hide().append('<input class="textbox" name="'+$(this).attr("name")+'-x'+'"/>');
})

http://jsfiddle.net/0ub2ht5s/

or if you prefer to create the element than the HTML

$('.someclass').each(function(){
    $input = $('<input>', {
        name: $(this).attr("name")+'-x',
    }).addClass('textbox');
    $(this).next('span').append($input);
})

http://jsfiddle.net/0ub2ht5s/2/

I removed .hide() from the fiddle otherwise you'd see nothing.

You could do it with the syntax you provided by giving append a function, but you'd be traversing unnecessarily, so don't do the following, it's here as an example:

$('.someclass').each(function(){
    $(this).next('span').append(function(){
        return '<input class="textbox" name="'+$(this).prev().attr("name")+'-x'+'"/>'
    });
})

http://jsfiddle.net/0ub2ht5s/1/

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337627

It's not possible with the syntax you have used. You need to store the original element in a variable:

var $el = $('.someclass');
$el.next('span').hide().parent().append('<input class="textbox" name="' + $el.attr("name") + '-x"/>');

Upvotes: 1

Related Questions