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

Accessing specific html elements values without changing the HTML

本文关键字:html 元素 访问 情况下      更新时间:2023-09-26

我是Javasript的新手,想知道如何访问特定的元素。我有超过20首歌曲的内容跨度。如果我已经在脚本中的一个变量中有跨度ID,例如"歌曲3",我该如何访问与该歌曲相关的"producedBy"类,更具体地说,是它里面的文本,在这种情况下,它说"无论天气如何"。不更改底层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>
...
document.getElementById("song_1").getElementsByClassName("producedBy")[0]

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

$("#song_1 > .songname").text()
document.getElementById("song_3").getElementsByClassName("producedBy")[0].innerHTML

document.getElementById

getElementsByClassName

element.innerHTML

演示