简体   繁体   中英

I am just trying to pass some javascript value from function func() to the tag "p".But it's not happening.Can anyone help me with this?

A part of the Html body:

<div id="d">
    <div class="imge">
        <img src="meter.jpg" width="450" height="350" alt="" />
        <h2>1234578  kWh</h2>
    </div>
</div>

This is the javascript function.

function func()
{
 document.getElementById("d").getElementsByClassName("imge").getElementsByTagName("h2")[0].innerHTML="String"
}

Is the above syntax correct?

Thanks in advance

document.getElementsByClassName method returns a HTMLCollection, so you at least need to use some index, like [0] to get the first element from this collection:

document.getElementById("d").getElementsByClassName("imge")[0].getElementsByTagName("h2")[0].innerHTML="String"

However it's much more convenient to use querySelector to retrieve HTML element by CSS selector:

function func() {
    document.querySelector('#d .imge h2').innerHTML = "String";
}

The code in func() should be document.getElementById("d").getElementsByClassName("imge")[0].getElementsByTagName("h2")[0].innerHTML="String"

as getElementsByClassName returns an array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM