Victor Czechov
Victor Czechov

Reputation: 237

How to get an element that was appended by before method?

the source example is kind of this

// block with caption
var caption_block = "<div class='caption-block'><h1>"+ options.title + "</h1><div class='pages'><a href='/' id='left_pg'></a><div id='counter'>"+ (i+1)+'/'+(elms+1)+"</div><a href='/' id='right_pg'></a></div></div>";

// put the elemnt with caption into the DOM
$('ul.slider').before(caption_block);

// by click in #counter TEST
$('a').bind('click',function(){

 $('#slider').find('#counter').text(" TEST ");

});

Unluck, but it's don't do anything at all.

The script can't find a div#counter. How to get it?

the html looks like

<div id="slider"><ul class="slider" /></div>

Upvotes: 0

Views: 64

Answers (4)

Adil
Adil

Reputation: 148110

Try this,

With previous

$('a').click(function(){

    $('#slider').prev('div').find('#counter').text(" TEST ");
});

or use parent of slider

$('a').click(function(){

     $('#slider').parent.find('#counter').text(" TEST ");
});

Directly with id

$('a').click(function(){

    $('#counter').text(" TEST ");
});

Upvotes: 1

CaffGeek
CaffGeek

Reputation: 22054

First, you're referencing slider by class name .slider, later you reference it by id #slider.

Second, you dont' have an anchor with id 'a' #a, you probably want to use $('a') to reference the anchor element.

Third, your selector is looking for #counter inside of slider, which it's not a child of. It was inserted before slider, not as a child.

See this fiddle for some working code http://jsfiddle.net/DyexP/2/

<ul id="slider" class="slider">ul</ul>​

var i = 1;
var elms = 10;
var options = {};
options.title = "title";

// block with caption
var caption_block = "<div class='caption-block'><h1>"+ options.title + "</h1><div class='pages'><a href='/' id='left_pg'></a><div id='counter'>"+ (i+1)+'/'+(elms+1)+"</div><a href='#' id='right_pg'>click me</a></div></div>";

// put the elemnt with caption into the DOM
$('ul.slider').before(caption_block);

// by click in #counter TEST
$('a').click(function(){
     $('#slider').parent().find('#counter').text(" TEST ");
});​

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Just write $('#counter').text(" TEST ")

also I think you need bind you link tag like below,

$('a', $('ul.slider')).click (function () {
    $('#counter').text(" TEST ")
});

Upvotes: 1

rjz
rjz

Reputation: 16510

The way you're using it, before is adding ul.slider as a sibling to the caption block containing div#counter. You could select for slider by checking their mutual parent for it:

$('a').click(function(){
  $('#slider').parent().find('#counter').text(" TEST ");
});

Upvotes: 1

Related Questions