如何在JavaScript中将p标签文本存入变量并显示在输入框中
Tag and Display It in an Input Field with JavaScript
Got it, let's walk through exactly how to pull this off. It's straightforward once you break it down into two key steps: grabbing the text from your paragraph, then shoving that text into your input box.
Step 1: Retrieve the text from the
tag
First, you need to target the
element in your DOM. There are a couple of common ways to do this:
- Use
document.querySelector('p')to grab the firsttag on the page. If you have a specific paragraph with an ID (like
<p id="source-text">Hello World</p>), usedocument.getElementById('source-text')for more precision. - Once you have the element, use either
textContentorinnerTextto get its text:textContentgets all text inside the element, including hidden content (like text in CSS-hidden spans).innerTextonly gets text that's visible on the page.
Store this text in a variable so you can reuse it later.
Step 2: Insert the text into the input field
Next, target your input element (again, using an ID is best for specificity, e.g., <input id="display-input" type="text">). Then set its value property to the variable you created in Step 1.
Full Working Example
Here's a complete code snippet you can copy and test:
<!-- HTML --> <p id="source-paragraph">This is the text we want to move to the input!</p> <input id="target-input" type="text" placeholder="Text will appear here"> <script> // Wait for the DOM to fully load before running our code document.addEventListener('DOMContentLoaded', function() { // Step 1: Get the text from the p tag const paragraphElement = document.getElementById('source-paragraph'); const paragraphText = paragraphElement.textContent; // Or use innerText if you prefer // Step 2: Put the text into the input field const inputElement = document.getElementById('target-input'); inputElement.value = paragraphText; }); </script>
Quick Notes to Avoid Headaches
- Always wrap your code in
DOMContentLoaded(or place your script at the end of the<body>tag) to make sure the browser has loaded all elements before your JS tries to access them. If you don't, you might get a "Cannot read properties of null" error. - If you have multiple
tags and want to grab text from all of them, use
document.querySelectorAll('p')and loop through the result:const allParagraphs = document.querySelectorAll('p'); let combinedText = ''; allParagraphs.forEach(para => { combinedText += para.textContent + ' '; }); inputElement.value = combinedText.trim(); - Double-check that your element IDs match exactly between your HTML and JS—typos are the #1 cause of issues here!
内容的提问来源于stack exchange,提问作者Ahsan Abrar

