简体   繁体   中英

How can i get the output of javascript object in div tag using document.write?

JavaScript Page:

I have created javascript function and inside it there is one object named Passenger which has three values ie name="A", age=30, reservationStatus=true. Now i want to print these values inside these three respective div's using document.write

HTML Page:

I have created three div tags with id="name", id="age", id="reservationStatus" and one button which has onclick event of javascript function.

Expected Results:

Name: A Age: 30 Reservation Status: true

Use document.getElementById() to identify an element with id(like div) and set a value to it as

document.getElementById("name").innerHTML =Passenger.name;
document.getElementById("age").innerHTML =Passenger.age;
document.getElementById("reservationStatus").innerHTML =Passenger.reservationStatus;

 const passenger = { name: 'A', age: 30, reservationStatus: true, }; const button = document.querySelector('button'); const showInfo = () => { document.querySelector('#name').textContent = `Name: ${passenger.name}`; document.querySelector('#age').textContent = `Age: ${passenger.age}`; document.querySelector('#reservationStatus').textContent = `Reservation status: ${passenger.reservationStatus}`; }; button.addEventListener('click', showInfo); 
 <button>Show</button> <div id="name"></div> <div id="age"></div> <div id="reservationStatus"></div> 

You can try like this:

 window.onload = () => { const passenger = { name: 'A', age: 30, reservationStatus: true }; const nameElement = document.querySelector('#name'); const ageElement = document.querySelector('#age'); const reservationStatusElement = document.querySelector('#reservationStatus'); const btnShowPassengerElement = document.querySelector('#btnShowPassenger'); // Hiding on window onload nameElement.innerHTML = ''; ageElement.innerHTML = ''; reservationStatusElement.innerHTML = ''; btnShowPassengerElement.addEventListener('click', (event) => { // Showing them on click of the button nameElement.innerHTML = passenger.name; ageElement.innerHTML = passenger.age; reservationStatusElement.innerHTML = passenger.reservationStatus; }); }; 
 group { display: inline-block; margin: 10px; } 
 <button id="btnShowPassenger">Show Passenger Details </button> <div> <div class="group"> <div> Name: </div> </div> <div class="group"> <div id="name"></div> </div> </div> <div> <div class="group"> <div> Age: </div> </div> <div class="group"> <div id="age"></div> </div> </div> <div> <div class="group"> <div> Reservation Status: </div> </div> <div class="group"> <div id="reservationStatus"></div> </div> </div> 

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