HTML तत्व के लिए जावास्क्रिप्ट का उपयोग करके एक विशिष्ट विशेषता बनाने के लिए HTML DOM createAttribute () विधि का उपयोग किया जाता है। createAttribute () विधि दिए गए नाम के साथ एक विशेषता बनाती है और विशेषता को एक Attr ऑब्जेक्ट के रूप में लौटाती है।
सिंटैक्स
createAttribute() विधि के लिए सिंटैक्स निम्नलिखित है -
document.createAttribute(attributename)
उदाहरण
आइए HTML DOM createAttribute() मेथड के लिए एक उदाहरण देखें -
<!DOCTYPE html> <html> <head> <title>CREATE ATTRIBUTE</title> <style> #DIV1{ margin-top:15px; width:250px; height:200px; border:2px solid blue; background-color:lightgreen; } </style> </head> <body> <p>Click the button to create a "class" attribute for the div element</p> <button onclick="attrCreate()">CREATE</button> <br> <div> <p>This is a sample div</p> </div> <script> function attrCreate() { var x = document.getElementsByTagName("div")[0]; var att = document.createAttribute("id"); att.value = "DIV1"; x.setAttributeNode(att); } </script> </body> </html>
आउटपुट
यह निम्नलिखित आउटपुट देगा -
क्रिएट बटन पर क्लिक करने पर -
उपरोक्त उदाहरण में -
हमने "DIV1" आईडी के साथ एक शैली बनाई है
#DIV1{ margin-top:15px; width:250px; height:200px; border:2px solid blue; background-color:lightgreen; }
हमने तब एक
तत्व है।
<div> <p>This is a sample div</p> </div>
फिर, हमने एक बटन बनाया है जो कि एक उपयोगकर्ता द्वारा क्लिक किए जाने पर attrCreate() फ़ंक्शन निष्पादित करेगा -
<button onclick="attrCreate()">CREATE</button>
attrCreate () फ़ंक्शन दस्तावेज़ ऑब्जेक्ट पर getElementsByTagName () विधि का उपयोग करके
function attrCreate() { var x = document.getElementsByTagName("div")[0]; var att = document.createAttribute("id"); att.value = "DIV1"; x.setAttributeNode(att); }