Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

html - Extract innerHTML from a Javascript function

I apologise in advance if this has already been asked, but I couldn't find it. If it has, please direct me to the page and I won't bother you.

I've used a Javascript function to extract inner HTML. I'm able to console.log this, but I'd like to insert it in a new node/part of the HTML.

For example:

<h2>Example text id="article"</h2>
<p>'insert javascript text'</p>

<p>example</p>
<p>example</p>
<p>example id="pToExtract"</p> <--! this is the text i'd like to extract. I would like to feature it higher up in the html page, as well as here. -->

this is the function i've used to extract the text:

function printFirstLine(elem) {
  let firstLine = document.getElementById(elem);
  console.log(firstLine.innerHTML)
}
printFirstLine ("pToExtract")// this works. i can see the text in the console

the function i've used to place it where i'd like is:

let newText = '';
let menu = document.getElementById ('article');
let li = document.createElement('p');
li.textContent= newText;

menu.insertBefore(li, menu.firstElementChild.nextSibling); 

this sort of works if i put text/a string on 'newText', and if I put the function name there it just returns the function, ie function () {} etc.

is there anyway to return the actual value/innerHTML of the function to say a new variable, so i can use it in the place of newtext or another way to accomplish this.

thank you


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not sure if I understand your question correctly but are you looking for this?

function printFirstLine(elem) {
  const firstLine = document.getElementById(elem);
  return firstLine.innerHTML; // here return the value
}

const newText = printFirstLine( 'pToExtract' );

Also I think you meant to write this:

<p id="pToExtract">example</p>

Instead of this:

<p>example id="pToExtract"</p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...