简体   繁体   中英

Replacing a line of code in html

Is it possible to use javascript to take this code for example:

<form>
<input type="text" id="text">
<input type="button" value="button" onclick="the function I need to use">
</form>

and change line #2 to this on the onclick event in line 3 with javascript:

<input type="text" id="text" style="width: 25px;">

So basically, I need to know if I can use javascript to replace a certain line of code with a completely different line of code, so that I can do things like make images that change when I click on them, and change back when I click on them again. Please try to explain your answer. I only understand html by asking questions and finding what I need when I need it. I do not actually KNOW html. If you can answer my question, it would be greatly appreciated. Thank you so much.

To set the width of the attribute.. Please Do this...

document.getElementById('text').setAttribute('style','width:25px');

if u want to remove it then at that tiem u can use

document.getElementById('text').removeAttribute('style','width:25px');
document.getElementById('text').style.width="25px";

The above should work.

It takes the element by its ID text and applies the style of "width=25px" to it.

Demo: http://jsfiddle.net/s24ZW/

yes you can. Use 'setAttribute' or 'getAttribute' property for setting and retrieving values.

var inputText=document.getElementById('text');
inputText.setAttribute('style','width:25px');

OR

inputText.style.width='25px';

Updated Code:-

<form>
<input type="text" id="text">
<input type="button" value="button" onclick="the function I need to use">
</form>

<script>
var inputText=document.getElementById('text');
    inputText.setAttribute('style','width:25px');
</script>

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