How to Change the Name of an Element in Dom

How can I change the name of an element in DOM?

Could you use importNode() to copy the childNodes of your <identity> element to a newly created <person> element?

function changeName($node, $name) {
$newnode = $node->ownerDocument->createElement($name);
foreach ($node->childNodes as $child){
$child = $node->ownerDocument->importNode($child, true);
$newnode->appendChild($child, true);
}
foreach ($node->attributes as $attrName => $attrNode) {
$newnode->setAttribute($attrName, $attrNode);
}
$newnode->ownerDocument->replaceChild($newnode, $node);
return $newnode;
}

$domElement = changeName($domElement, 'person');

Perhaps something like that would work, or you could try using cloneChild().

Edit: Actually, I just realized that the original function would lose the placement of the node. As per the question thomasrutter linked to, replaceChild() should be used.

Javascript: How to change a nodes name?

You cannot just change an element. You have to create a new one. E.g.:

var div = document.getElementsByTagName("div")[0];
var p = document.createElement('p');
p.innerHTML = div.innerHTML;
div.parentNode.replaceChild(p, div);

But this could lead to invalid markup, if the original element contains nodes that cannot be descendants of the new node.

Reference: document.createElement, Node.replaceChild


Note: A better version (because it doesn't depend on serializing DOM to text and back and preserves attributes), can be found at https://stackoverflow.com/a/8584158/218196 .

replace specific tag name javascript

var element = document.getElementById("93");
element.outerHTML = element.outerHTML.replace(/wns/g,"lmn");

FIDDLE

Is there a better way to change a DOMElement-tagName property in php?

Yes, this how you have to do it -- the reason is that you're not just changing the value of a single attribute (tagName), you're actually changing the entire element from one type to another. Properties such as tagName (or nodeName) and nodeType are read-only in the DOM and set when you create the element.

So, creating a new element and moving in place of the old one exactly as you're doing, with DOMNode::replaceChild, is the correct operation.

I'm not sure what you mean by "unwanted side effect of nulling all the logic behind the control" -- if you clarify I might be able to give you guidance there.

It sounds like you might not want to have ServerTag inherit from DOMElement and instead you may want to link these two objects through some other pattern, such as composition (i.e. so a ServerTag "has a" DOMElement instead of "is a" DOMElement) so that you're merely replacing the DOMElement object associated with your ServerTag Textbox object.

Or a longer-shot guess is you might be running into issues just copying the attributes (i.e. textarea has required attributes, like rows and cols, that input does not).

Changing HTML DOM element name dynamically

I just change the elements' names before the form is submitted to the server. No need for dynamic changing, i.e., when an element is removed and and a new one is added. It's more convenient.

How can I change an element's class with JavaScript?

Modern HTML5 Techniques for changing classes

Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

document.getElementById("MyElement").classList.add('MyClass');

document.getElementById("MyElement").classList.remove('MyClass');

if ( document.getElementById("MyElement").classList.contains('MyClass') )

document.getElementById("MyElement").classList.toggle('MyClass');

Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.

Simple cross-browser solution

The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass";

(You can use a space-delimited list to apply multiple classes.)

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

document.getElementById("MyElement").className += " MyClass";

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */

An explanation of this regex is as follows:

(?:^|\s) # Match the start of the string or any single whitespace character

MyClass # The literal text for the classname to remove

(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be the end of the string or space)

The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

To check if a class is already applied to an element:

The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )


### Assigning these actions to onClick events:

Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onClick="this.className+=' MyClass'") this is not recommended behavior. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.

The first step to achieving this is by creating a function, and calling the function in the onClick attribute, for example:

<script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onClick="changeClass()">My Button</button>

(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)

The second step is to move the onClick event out of the HTML and into JavaScript, for example using addEventListener

<script type="text/javascript">
function changeClass(){
// Code examples from above
}

window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>

(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)



JavaScript Frameworks and Libraries

The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.

Whilst some people consider it overkill to add a ~50  KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.

(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)

The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).

(Note that $ here is the jQuery object.)

Changing Classes with jQuery:

$('#MyElement').addClass('MyClass');

$('#MyElement').removeClass('MyClass');

if ( $('#MyElement').hasClass('MyClass') )

In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:

$('#MyElement').toggleClass('MyClass');


### Assigning a function to a click event with jQuery:
$('#MyElement').click(changeClass);

or, without needing an id:

$(':button:contains(My Button)').click(changeClass);


How to change the Element Name in XML using minidom + python

You can change the node name by setting the tagName attribute
Try this,

tag_ccc = dom2.getElementsByTagName("CCC")[0]
tag_ccc.tagName = "XXX"

This should change the tag name to "XXX", below is the test code i used to confirm this using python 2.7

from xml.dom.minidom import parse, parseString
xml ="""<CCC><BBB>This is test</BBB></CCC>"""
dom = parseString(xml)
tag_ccc = dom.getElementsByTagName("CCC")[0]
tag_ccc.tagName = "XXX"
print tag_ccc.toxml("utf-8")

Hope this helped.



Related Topics



Leave a reply



Submit