Changing XML tag names with Javascript - javascript

I have a scenario where I have to remove the numbers from the name of the xml tag. For example, if there is a tag <xxx1>1234</xxx1>, I need an output as <xxx>1234</xxx>. I surfed through the net and was not able to find a solution. Please help.

You could take a dom elements children and append to a new dom element in its place rather than changing the element details itself.
Pseudo code:
curElementContent = get element from dom and get its contents
newElement = create new dom element
append curElementContent to newElement
remove curElement from dom and insert newElement.

You could give this a try:
tags.replace(/<xxxx\d>/gi, '<xxxx>').replace(/<\/xxxx\d>/gi,'</xxxx>');
Where tags contains the string you need to update.

Got it working by converting the xml into an xml string and using the below regex.
xmlString = xmlString.replace(/\d+>/g, '>');

Related

Vanilla JavaScript replace element

I've looked around and can't seem to find a solution to directly replacing an element with a HTML string using vanilla JavaScript (not jQuery).
I'm storing a bunch of svg's in a directory that's publicly accessible, and I want to be able to include them in my files via the image tag <img src="path/to/svgs/example.svg">. However, this comes with its drawbacks as they can't be coloured/styled when they're pulled in as an image (to my knowledgE).
I discovered this example jQuery Image to SVG but obviously this uses jQuery's replaceWith function. I'm trying to replicate the functionality but struggling with the aforementioned function. All examples I've found end up creating a parent div element, and appending the new HTML to that newly created element.
TL;DR: Can I directly replace an element (IMG to SVG) using vanilla JavaScript without creating parent nodes?
jQuery is also using JavaScript behind replaceWith method, so if you want to replace one element with another you need to do next steps:
Create new element
Add it after/before an element that needs to be replaced
Then remove original element
e.g
If we have HTML list
<ul>
<li>before</li>
<li id="my-element">My element</li>
<li>after</li>
</ul>
and we want to replace list item, with id "my-element", with the new element then we need to do next:
//get reference to element that we want to replace
var elementToReplace = document.getElementById('my-element');
//create new element which will replace existing element
var newLi = document.createElement('li');
//just setting html in it
newLi.innerHTML = 'Just added';
//getting parent element reference and executing method "insertBefore" passing our new element and reference of element that we want to replace
elementToReplace.parentNode.insertBefore(newLi, elementToReplace.nextSibling);
//then we remove original element
elementToReplace.parentNode.removeChild(elementToReplace);
I hope this helps.
Assuming you have already loaded the SVG into a string (via XmlHttpRequest, fetch etc). Then you can parse it using the DOMParser.
var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingSVGSource, "image/svg+xml");
See: Parse SVG and add it to a svg element
Then you can replace the original <img> using something like the insertBefore/removeChild method that Senad suggests.

JS: Moving an anchor with insertAdjacentHTML only appends the href, not the element

I'm trying to move an anchor tag from one element to another. When I do this, the only thing appended is the anchors href, not the element itself. Why is this and how can I fix it?
I need a solution in Javascript only as jQuery isn't being used
Thanks for any help!
Fidde: https://jsfiddle.net/p7g7mkxs/
What I've tried:
<p class="hello">hello</p>
<p class="hello">helloLINK</p>
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0]);
I've also tried using different variations of selecting my elements, like getElementsByTagName or appending it differently with innerHTML - Everything I've tried has given me the same result.
You use insertAdjacentHTML with HTML (a string), not with an actual element. If you pass it an element, the element is converted to string (like String(theElement)). In the case of an HTMLAnchorElement, that means you just get the href. Proof:
console.log(
String(document.querySelector("a"))
);
Hey
To append an element to the end of another element's child list, use appendChild:
var hello = document.querySelectorAll('.hello');
hello[0].appendChild(hello[1].querySelector('a'));
(To insert it elsewhere, use insertBefore. Actually, you can use insertBefore in all cases if you like, just use null as the reference element when adding to the end.)
Also note that when you only want the first match, rather than querySelectorAll(/*...*/)[0], use querySelector(/*...*/), which returns the first match or null.
In addition to what #t-j-crowder said, you can also use outerHTML to accomplish the task:
var hello = document.querySelectorAll('.hello');
hello[0].insertAdjacentHTML('beforeEnd', hello[1].querySelectorAll('a')[0].outerHTML);

What is the difference between appendChild, insertAdjacentHTML, and innerHTML

I want to know what the difference is between appendChild, insertAdjacentHTML, and innerHTML.
I think their functionality are similar but I want to understand clearly in term of usage and not the execution speed.
For example, I can use innerHTML to insert a new tag or text into another tag in HTML but it replaces the current content in that tag instead of appends.
If I would like to do it that way (not replace) I need to use insertAdjacentHTML and I can manage where I want to insert a new element (beforebegin, afterbegin, beforeend, afterend)
And the last if I want to create (not insertion in current tag) a new tag and insert it into HTML I need to use appendChild.
Am I understanding it correctly? Or are there any difference between those three?
element.innerHTML
From MDN:
innerHTML sets or gets the HTML syntax describing the element's descendants.
when writing to innerHTML, it will overwrite the content of the source element. That means the HTML has to be loaded and re-parsed. This is not very efficient especially when using inside loops.
node.appendChild
From MDN:
Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.
This method is supported by all browsers and is a much cleaner way of inserting nodes, text, data, etc. into the DOM.
element.insertAdjacentHTML
From MDN:
parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. [ ... ]
This method is also supported by all browsers.
....
The appendChild methods adds an element to the DOM.
The innerHTML property and insertAdjacentHTML method takes a string instead of an element, so they have to parse the string and create elements from it, before they can be put into the DOM.
The innerHTML property can be used both for getting and setting the HTML code for the content of an element.
#Guffa did explain the main difference ie innerHTML and insertAdjacentHTML need to parse the string before adding to DOM.
In addition see this jsPerf that will tell you that generally appendChild is faster for the job it provides.
One that I know innerHTML can grab 'inner html', appendChild and insertAdjacentHTML can't;
example:
<div id="example"><p>this is paragraph</p><div>
js:
var foo = document.getElementById('example').innerHTML;
end then now
foo = '<p>this is paragraph</p>';
DOCS:
appendChild
insertAdjacentHTML
innerHtml
innerHTML vs appendChild() performance
insertAdjacentHTML vs innerHTML vs appendChild performance
the main difference is location (positioning) :
(elVar mean element saved to variable)
** elVar.innerHTML: used to sets/get text and tags (like ) inside an element (if u use "=" it replace the content and "+=" will add to the end.
** divElvar.appendChild(imgElVar): to add pure element to the end of another element (or start with prepend) .
** insertedElVar.insertAdjacentElement(beforebegin,targetElvar): it insert element into spicific location before elVar (after it with "afterend").
-innerText: can replace/get/insertOnEnd text.but can read tags and text inside element with display:hidden , cant insert on start .
-innercontent : show all text inc hidden , cant read html tags and it put empty spaces instead of them , cant insert on start
-innerHTML: read all set all , cant insert on start
-prepend : insert text at start of elvar (but cant use to get/replace text or html)
prepend was needed for start, after it made its easy to make append , not for a need , its just bcz lol

Get the HTML that makes up an element in Jquery or Javascript?

How do I get the HTML that makes up an element using Jquery or Javascript?
For example if I have an element that looks like
<div id="theDivIWant" class="aClassName" style="somestyle: "here"></div>
I can grab a reference to it using
var x = document.getElementById("theDivIWant")
or $("#theDivIWant")
but how can I actually retrieve the string?
"<div id="theDivIWant" class="aClassName" style="somestyle: "here"></div>"
the outerHTML property will give you what you want in IE; in webkit and firefox, you can get the innerHTML of the parent and filter it:
var whatYouWantPlusItsSiblings = $('#target').closest().html();
From there, you can strip the content you don't need. Alternatively, if you have control over the markup, you can surround your target with another well-known element and get that parent's innerHTML.
You could implement outerHTML with jQuery.
if it is the only child of its parent, this should work:
$('#theDivIWant').parent().html();
If it is not the only child, you may be able to combine the above code with some regex to extract only it from the results.

Append a jQuery element to a string that contains html

I have a jQuery wrapped element which I would like to append to a html row. I can't wrap my head around this, since append() seemingly accepts strings but not existing jQuery elements (I might be mistaken here).
I have a following setup:
var row='<tr><td>data1</td><td>data2</td><td>';
var img=$('<img src="path/to/img.png"');
img.click(myClickHandler);
Now what I'm trying to do is to append this img element to my row and 'close' the row with a closing tag.
I'm doing it as follows:
var jRow=$(row);
jRow.append(img);
jRow.append('</td></tr>');
After my row is ready I append it to my table:
$('#tableId').append(jRow);
Well, all above doesn't work, because I get [Object Object] instead of image tag in my added row.
My goal is to have a row with an image in last cell and a working click handler.
Pleease, help.
When you pass a string to append() it is first "converted" to a DOM element/collection. So, every single string you pass to append() must be valid HTML/XHTML; you can't add bits of string on later. The image can still be appended to the table row even if you close the tags beforehand. E.g.
var row='<tr><td>data1</td><td>data2</td><td></td></tr>';
var img=$('<img src="path/to/img.png"/>');
img.click(myClickHandler);
var jRow = $(row);
$('td:last', jRow).append(img);
When you pass anything to append() or html() or prepend() (or any other similar method) try to forget about strings; what you just passed is no longer a string; it has been parsed as HTML and has been added to the document as a DOM element (or a number of DOM elements).
I am not 100% sure, but I think HTML fragments should always be "complete", meaning that adding just "</td></tr>" will not work.
A solution would be to build a string with a complete HTML fragment, and then append it, instead of appending the pieces one at a time. You can always add the click handler after you created your jQuery object, like this:
jRow.find("img").click(function () { ... });
How about trying with jRow.html(), like this?
$('#tableId').append(jRow.html());
It should return you the actual HTML contents instead of the jQuery-wrapped element (jQuery object), which is probably what causes the problem, since append() expects to get a String to append.
Attributes/html()
Manipulation/append()

Categories