在不更改HTML的情况下访问特定的html元素值

时间:2012-08-06 21:56:17

标签: javascript

我是Javasript的全新手,想了解如何访问特定元素。我有20多首歌曲内容。如果我已经在脚本中的变量中有例如“歌曲3”的跨度ID,我该如何访问与该歌曲相关的“generatedBy”类,更具体地说,是在其中保存的文本,在这种情况下是“不管是什么”天气”。不改变底层HTML?

非常感谢任何帮助以帮助理解javascript。感谢。

    <div class="Artist Song">
    <span id="song_1" class="song">   
       <span class="artistname">MJ</span>
        <span class="songname">Billie Jean</span>
        <span class="email" style="whatever"><strong>neverland@ranch.com</strong></span>
        <span class="recordlabel">def jam</span>
        <span class="age">34 years</span>
        <span class="album">Album:<strong>Bad</strong></span>
        <span class="dateReleased" style="display:none">whatever</span>
        <span class="producedBy" style="display:none">Produced by Quincy jones</span>
    </span>
</div>

<div class="Artist Song">
    <span id="song_2" class="song">   
       <span class="artistname">Prodigy</span>
        <span class="songname">Firestarter</span>
        <span class="email" style="whatever"><strong>firestarter@twisted.com</strong></span>
        <span class="recordlabel">whatever</span>
        <span class="age">whatever</span>
        <span class="album">Album:<strong>Fat of the land</strong></span>
        <span class="dateReleased" style="display:none">whatever</span>
        <span class="producedBy" style="display:none">whatever</span>
    </span>
</div>

<div class="Artist Song">
    <span id="song_3" class="song">   
       <span class="artistname">Whoever</span>
        <span class="songname">Whatever</span>
        <span class="email" style="whatever"><strong>whatever@wherever.com</strong></span>
        <span class="recordlabel">whatever</span>
        <span class="age">whatever</span>
        <span class="album">Album:<strong>Whatever</strong></span>
        <span class="dateReleased" style="display:none">whatever</span>
        <span class="producedBy" style="display:none">whatever the weather</span>
    </span>
</div>

<div class="Artist Song">
    <span id="song_4" class="song">   
       <span class="artistname">Whoever</span>
        <span class="songname">Whatever</span>
        <span class="email" style="whatever"><strong>whatever@wherever.com</strong></span>
        <span class="recordlabel">whatever</span>
        <span class="age">whatever</span>
        <span class="album">Album:<strong>Whatever</strong></span>
        <span class="dateReleased" style="display:none">whatever</span>
        <span class="producedBy" style="display:none">whatever</span>
    </span>
</div>

...

3 个答案:

答案 0 :(得分:2)

document.getElementById("song_1").getElementsByClassName("producedBy")[0]

答案 1 :(得分:0)

使用jQuery进行简单的dom操作:

$("#song_1 > .songname").text()

答案 2 :(得分:0)

document.getElementById("song_3").getElementsByClassName("producedBy")[0].innerHTML

document.getElementById

getElementsByClassName

element.innerHTML

DEMO