Have a value of an HTML paragraph | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Have a value of an HTML paragraph

Hi every body, please how to have a value of an HTML paragraph with JS ?

22nd Jul 2017, 10:30 PM
ADAMOU AMADOU Abdoul Razak
ADAMOU AMADOU Abdoul Razak - avatar
4 Answers
+ 5
Correct syntax is: var pars = document.getElementsByTagName('p'); "tagNAME", and notice the 's' to element: this will return an array-like object of all 'p' element... To target the right element and only it, give it an 'id' attribute, use rather use: var par = document.getElementById('myPar'); Notice than there's no 's' to elements, ids needs to be unique, so this method return an unique element ^^ Once you've get the element reference, you can access its 'innerHTML' attribute: var text1 = pars[0].innerHTML; // get the first <p> value var text2 = par.innerHTML; // get the <p id="myPar"> value 'innerHTML' return (and/or set) the Html content of an element... you can also want to read/write the plain text content: var text3 = par.textContent; // get only text value (without tags) [edit] In code playground, if you write code in JS tab, you need to wait for DOM ready before trying to access it through this kind of methods, because JS tab is linked at end of <head> part of Html, before DOM loaded/initialized... Simplest way to be sure that you doesn't access DOM too sooner, is to embed all you JS code inside an anonymous function assigned to 'onload' event of window: window.onload = function() { /* all your code */ };
23rd Jul 2017, 12:13 AM
visph
visph - avatar
+ 3
var paragraph = document.getElementByTag('p'); var paragraphValue = paragraph.innerHTML;
22nd Jul 2017, 10:53 PM
LordGhostX
LordGhostX - avatar
+ 3
It's alright it works. Thank again
22nd Jul 2017, 11:13 PM
ADAMOU AMADOU Abdoul Razak
ADAMOU AMADOU Abdoul Razak - avatar
+ 2
Thank you for your reply but it return me 'undefined'
22nd Jul 2017, 11:03 PM
ADAMOU AMADOU Abdoul Razak
ADAMOU AMADOU Abdoul Razak - avatar