Computer Science, asked by amitabhdas8958, 1 year ago

Explain the three approaches of element access in javascript with suitable examples

Answers

Answered by 123SMJ456
0

Answer:

Javascript provides the ability for getting the value of an element on a webpage as well as dynamically changing the content within an element. Getting the value of an element To get the value of an element, the getElementById method of the document object is used. For this method to get the value of an element, that element has to have an id given to it through the id attribute. Example:

<script type="text/javascript">

function getText()

{

//access the element with the id 'textOne' and get its value //assign this value to the variable theText var

theText = document.getElementById('textOne').value;

alert("The text in the textbox is " + theText);

}

</script>

<input type="text" id="textOne" />

<input type="button" value="Get text" onclick="getText()" />

Changing the content within an element To change the content within an element, use the innerHTML property. Using this property, you could replace the text in paragraphs, headings and other elements based on several things such as a value the user enters in a textbox. For this property to change the content within an element, that element has to have an 'id' given to it through the id attribute.  

Example:

<script type="text/javascript">

function changeTheText()

{ //change the innerHTML property of the element whose id is 'text' to 'So is HTML!' document.getElementById('text').innerHTML = 'So is HTML!'; }

</script>

<p id="text">Javascript is cool!</p>

<input type='button' onclick='changeTheText()' value='Change the text' />

You can also change the text of elements based on user input:

Example:

<script type="text/javascript">

function changeInputText(){

/* change the innerHTML property of the element whose id is 'theText' to the value from the variable usersText which will take the value from the element whose id is 'usersText' */

var usersText = document.getElementById('usersText').value; document.getElementById('theText').innerHTML = usersText;

}

</script>

<p id="theText">Enter some text into the textbox and click the buttton</p>

<input type="text" id="usersText" />

<br />

<input type="button" onclick="changeInputText()" value="Change the text" />

Similar questions