Em1
Em1

Reputation: 1095

Access to another child of parent

I've HTML like that:

<div>
  <table>
  </table>
  <div>
  </div>
</div>

In JavaScript I have already access to this table. Now I want to get the other child element (div) from parent.

var par = table.parentNode;
var ch = $(par).children("div").first();

Actual I have an object, but when I try to add HTML like

ch.innerHTML = "Test";

I've no success. The text test is not added. If I would add the text to par itself, it works, but as soon as I get children with jquery, it does not work.

For debugging I alert the par and the ch. In case of par I see that I have HTMLDivElement, in case of ch it is only an Object.

What I am doing wrong?

Hint: Giving an id to the div and get it this way is not a solution for my application!

Upvotes: 0

Views: 151

Answers (3)

Esailija
Esailija

Reputation: 140220

ch is referring to a jQuery collection of elements (alerts [object Object]) so what should work is

ch[0].innerHTML = "Test"; (ch[0] = [object HTMLDivElement])

or

 ch.html( "Test" );

I do not recommend the former in any case but just pointing out what went wrong.

Upvotes: 1

pimvdb
pimvdb

Reputation: 154838

Given the table and wanting the div, you can use .siblings:

$(table).siblings('div').first().html('Test');

Upvotes: 0

Kokos
Kokos

Reputation: 9121

You are using jQuery and Javascript in a very strange way, why are you using Javascript methods on jQuery objects?

If $(par).children("div").first(); contains the correct object, you can set its html through jQuery like this:

$(par).children("div").first().html('test');

Upvotes: 3

Related Questions