eightArmCode
eightArmCode

Reputation: 185

dynamically assign text to <a> from <li>

Using jquery 1.8.3

I am creating a function which creates an "li" element and sets some properties, including establishing an event listener.

$(this).closest('a').text(text); //$(this) is the li tag, and it does show that in the browser if you step through

The dom structure looks like this:

<div>
    <a></a>
    <div>
        <ul>...</ul>
    </div>
</div>

If you follow it in the debugger, both the .text() method and "text" variable are being populated with the correct info. There is something going on with the assignment part that I can't track. I am sure it is something stupid and obvious I am missing, but I could use some help getting over this hump.

If you need more info, please let me know.

Upvotes: 2

Views: 69

Answers (2)

Ligth
Ligth

Reputation: 330

You have to use html() function from jQuery:

$(document).ready(function(){

$("#element li ").click(function(){
  $("#linki").html($(this).html());

  });
});



  <a href="" id="linki" ></a>

    <a></a>
    <div>
        <ul id="element">
          <li>Hello</li>

        </ul>
    </div>

live example http://jsbin.com/opoqid/46/edit

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

The anchor tag is not the ancestor of the li .. Rather it is a sibling of the div in which it is encased..

You are looking for this I belive

$(this).closest('div').prev('a').text(text);

Upvotes: 3

Related Questions