简体   繁体   中英

How to Change HTML Tags Using Javascript

I have some HTML code that looks like this:

<textarea name="message"></textarea>

And I would like to change it to this:

<textarea maxlength="300" name="message"></textarea>

How can I accomplish this using Javascript? I have tried a lot of different code from a lot of different places, but none of them seem to work. If need be, I will accept CSS code too.

Here's how you do it if you aren't using jQuery (highly recommended):

var myelement = document.getElementsByName('message')[0];
myelement.setAttribute('maxlength',300);

Here's the jsFiddle

使用jquery匹配tag元素,然后使用.attr()函数。

Since you're not using jQuery:

<textarea id="text" name="message"></textarea>
var element = document.getElementById("text");
element.setAttribute("maxlength","300");

Example

document.querySelector('[name="message"]').setAttribute('maxlength', 300)
$('textarea').attr('maxlength', 300);

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