Wasteland
Wasteland

Reputation: 5379

javascript - select a div within a particular div

The content of the divs is going to be populated with javascript json. Now, I know how to select a div in javascript:

var hsc = document.getElementByID("hsc");

But how would I refer to eg. the title but only in the hsc div.

<div id="hsc">
    <div id="title"></div>
    <div id="jobs"></div>
...
</div>

<div id="cc">
    <div id="title"></div
    <div id="jobs"></div>
</div>

On a separate note, wouldn't 'title' and 'jobs' be better classified as classes, and not ids?

Upvotes: 0

Views: 1703

Answers (3)

Smudoo
Smudoo

Reputation: 547

Just try

<div id="hsc">
    <div id="a" class="title"></div>
    <div id="b" class="jobs"></div>
...
</div>

<div id="cc">
    <div id="c" class="title"></div
    <div id="d"class="jobs"></div>
</div>

Because your HTML code is invalid because the id is already taken.

Upvotes: 0

baao
baao

Reputation: 73241

This would work:

var hsc = document.querySelectorAll("#hsc > .title");

But you need to change to valid html and use unique IDs and classes instead:

<div id="hsc">
    <div class="title"></div>
    <div class="jobs"></div>
...
</div>

<div id="cc">
    <div class="title"></div>
    <div class="jobs"></div>
</div>

Upvotes: 1

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

IDs must be unique in HTML.

Change them to classes, and then you can use querySelector() to target them:

document.querySelector('.hsc .title').style.color= 'blue';
document.querySelector('.cc .title').style.color= 'red';
<div class="hsc">
    <div class="title">Make me blue!</div>
    <div class="jobs">Jobs</div>
</div>

<div class="cc">
    <div class="title">Make me red!</div>
    <div class="jobs">More jobs</div>
</div>

Upvotes: 1

Related Questions