简体   繁体   中英

How to add text to paragraphs on clicking button

I'm making a policy generator page. Where you input the text and get the output. But I'm facing the problem: problem (I'm not able to generate multiple codes. Mean I want to generate privacy policy terms and conditions in different div areas eg:( <p id="p2"><code class="generator__markup-generated"></code></p> ))

Here's my code

 const generate = document.querySelector('.generate-markup'); generate.addEventListener('click', () => { const varName = document.querySelector('#company').value; const idName = document.querySelector('#url').value; const markupContainer = document.querySelector('.generator__markup-generated'); //sample paragraph policy const markup = ` ${varName} have a website ${idName} which you can use to generate policies. `; markupContainer.textContent = markup; }); function copyToClipboard(element) { var $temp = $("<input>"); $("body").append($temp); $temp.val($(element).text()).select(); document.execCommand("copy"); $temp.remove(); }
 <div class="generator__markup" style="font-size: 18px; text-align: center;"><label>Company Name:</label>&nbsp;<input id="company" type="text" />&nbsp;</div> <div class="generator__markup" style="font-size: 18px; text-align: center;"><label>Website Url:</label>&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<input id="url" type="text" />&nbsp;</div> <button class="generate-markup">Generate Code</button> </br> <div class="generator__markup"> <h1 style="text-align: center;">Copy Your Page</h1> <p id="p2"><code class="generator__markup-generated"></code></p> <center> <button onclick="copyToClipboard('#p2')">Click To Copy</button></center>

please help in this thing

To modify HTML elements, you use the JavaScript DOM API.

It appears that the text for the policies is stored in the markup variable. We need to take this text and put it inside the element as innerText .

First, we need to get a reference to the DOM element. I see that you have selected the element using querySelector to grab a class attribute. This selects all elements with that class. You need to use an id attribute instead to select a single element. Let's assume you assign the id attribute of the paragraph to generated-markup-paragraph .

So, with this corrected code, we can now set the text of the paragraph:

const markupParagraph = document.getElementById("generated-markup-paragraph");
markupParagraph.innerText = markup;

That code should go in the place of the markupContainer.textContent = markup line.

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