I am trying to create a general function that will extract a div content (with nested elements) and save it locally in an HTML file.
Basically I get the div innerHTML, wrap it in html/head/body tags and then save it:
function div2html() {
var inner=document.getElementById("div2save").innerHTML;
var html="<html><head></head><body>"+inner+"</body></html>";
saveTextAsFile("div2html.html", html);
}
See a working version here: jsfiddle
However I am not sure how to handle classes. As you can see the class in the sample (bigbold) is not embedded in the new HTML. I need some way to get all the classes used in the div and then add them (or the computed styles ?) to the html I generate .. is this possible ? is there any other way around it ?
Try including style element .outerHTML within saved html
function div2html() {
var inner=document.getElementById("div2save").innerHTML;
var style = document.getElementsByTagName("style")[0].outerHTML;
var html="<html><head>"+style+"</head><body>"+inner+"</body></html>";
saveTextAsFile("div2html.html", html);
}
jsfiddle http://jsfiddle.net/fb6s763w/1/
Alternatively, using window.getComputedStyle() to select only css of #div2save child node
function div2html() {
var inner = document.getElementById("div2save");
var style = window.getComputedStyle(inner.children[0]).cssText;
var html = "<html><head><style>"
+ "." + inner.children[0].className
+ "{" + style + "}"
+ "</style></head><body>"
+ inner.innerHTML + "</body></html>";
saveTextAsFile("div2html.html", html);
}
jsfiddle http://jsfiddle.net/fb6s763w/2/
Looks like this might be able to help you out:
https://github.com/Automattic/juice
If the CSS of the page is not big, a simple solution is to include it all in the saved html as suggested by guest271314 above with
var style = document.getElementsByTagName("style")[0].outerHTML;
see jsfiddle
A more comprehensive solution extracts the classes from the div and then adds only the rules of those classes to the div (Using code from How do you read CSS rule values with JavaScript?)
function div2html(divId) {
var html = document.getElementById(divId).innerHTML;
// get all css classes in html
var cssClasses = [];
var classRegexp = /class=['"](.*?)['"]/g;
var m;
while ((m = classRegexp.exec(html))) cssClasses = cssClasses.concat(cssClasses, m[1].split(" "));
// filter non unique or empty cssClasses
cssClasses = cssClasses.filter(function (item, pos, self) {
return item && self.indexOf(item) == pos;
});
// get html of classes
var cssHtml = '';
for (var i = 0; i < cssClasses.length; i++) cssHtml += getRule('.' + cssClasses[i]);
// assemble html
var html = "<html><head><style>" + cssHtml + "</style></head><body>" + html + "</body></html>";
console.log(html);
saveTextAsFile("div2html.html", html);
}
see jsfiddle
I have a Function which makes an ajax call and then return a piece of html that is inserted into a table's td element. using element.innerHTML=ajaxResult; Now I want to access the elements in the ajaxResult that have the name attribute as special. So I do a document.getElementsByName('special') and expect to get 4-5 elements. But I actually get none.
This makes it impossible for me to access those elements and I am stuck. Please help me resolve this. Thanks in Advance!
I think this is related to the dom not reloading after I set innerHTML. But not sure how to reload it.
I am using IE8 in IE8 compatibility view and IE7 standards :(
EDIT
This is my function
function handleStateChange()
{
if(ajaxRequest.readyState==4 && ajaxRequest.status==200) {
var responseStr = ajaxRequest.responseText;
var splitResult = responseStr.split("$$$$$$$$$$$$$$$$$$$$");
var leftHtml= splitResult [0];
var rightHtml= splitResult [1];
document.getElementById("div1").innerHTML=leftHtml;
if(rightHtml !="") {
document.getElementById("div2").innerHTML=rightHtml;
}
if(splitResult.length >=3 ){
var appActionflag = splitResult [2];
document.getElementById("userAction").innerHTML=appActionflag;
}
if(splitResult.length >= 4 ){
var userId = splitResult [3];
document.getElementById("userId").innerHTML=userId;
}
reverseDNASwitch();
var grpList = document.getElementsByName('parmGrpId');
alert('javascript is working! Found:'+grpList.length);
for(var i=0;i<grpList.length;i++){
alert('Got GroupId: '+ (i));
var grpTd = grpList[i];
grpTd.innnerHTML='Hi';
}
}
}
If the table cell you're adding to is, itself, in the DOM, that should work. (And so I may have to delete this answer; originally I thought document.getElementsByName had been deprecated, but I was mistaken). Here's an example using getElementsByName:
Live Copy | Live Source
(function() {
// Get the target
var target = document.getElementById("target");
// Dynamically add content
target.innerHTML =
'<div name="special">special 1</div>' +
'<div name="special">special 2</div>' +
'<div name="special">special 3</div>';
// Get those elements
var list = document.getElementsByName("special");
// Prove we got them
var p = document.createElement('p');
p.innerHTML = "Found " + list.length + " 'special' elements";
document.body.appendChild(p);
})();
Of course, because it's a function of document, that will find all of the elements with name="special", not just the ones you added to the table cell.
The above does not work on IE if the elements aren't allowed to have the name attribute. So for instance, if you look for getElementsByName("special"). it will ignore <div name="special"> but find <input name="special">, because name is not a valid attribute for div elements. Details in this MSDN article. Worse, IE will include elements whose id matches, even though of course that has nothing to do with name. sigh
Unless you need to support IE7 and earlier (e.g., unless you're developing for China), you can use Element#querySelectorAll with the selector '[name="special"]'. That will look only within the element for elements that use that name attribute.
Example: Live Copy | Live Source
(function() {
// Get the target
var target = document.getElementById("target");
// Dynamically add content
target.innerHTML =
'<div name="special">special 1</div>' +
'<div name="special">special 2</div>' +
'<div name="special">special 3</div>';
// Get those elements
var list = target.querySelectorAll('[name="special"]');
// Prove we got them
var p = document.createElement('p');
p.innerHTML = "Found " + list.length + " 'special' elements";
document.body.appendChild(p);
})();
If you need to support IE7 or earlier, you might look at this other Stack Overflow question and my answer to it. The question points to this article about adding querySelectorAll to document, and my answer to the question talks about how to emulate that at an element-specific level.
So combining the code from that article with my answer to the other question and the examples above, we get:
Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="target"></div>
<script>
(function() {
// IE7 support for querySelectorAll. Supports multiple / grouped selectors and the attribute selector with a "for" attribute. http://www.codecouch.com/
if (!document.querySelectorAll) {
(function(d, s) {
d=document, s=d.createStyleSheet();
d.querySelectorAll = function(r, c, i, j, a) {
a=d.all, c=[], r = r.replace(/\[for\b/gi, '[htmlFor').split(',');
for (i=r.length; i--;) {
s.addRule(r[i], 'k:v');
for (j=a.length; j--;) a[j].currentStyle.k && c.push(a[j]);
s.removeRule(0);
}
return c;
}
})();
}
var qsaWorker = (function() {
var idAllocator = 10000;
function qsaWorkerShim(element, selector) {
var needsID = element.id === "";
if (needsID) {
++idAllocator;
element.id = "__qsa" + idAllocator;
}
try {
return document.querySelectorAll("#" + element.id + " " + selector);
}
finally {
if (needsID) {
element.id = "";
}
}
}
function qsaWorkerWrap(element, selector) {
return element.querySelectorAll(selector);
}
// Return the one this browser wants to use
return document.createElement('div').querySelectorAll ? qsaWorkerWrap : qsaWorkerShim;
})();
// Get the target
var target = document.getElementById("target");
// Dynamically add content
target.innerHTML =
'<div name="special">special 1</div>' +
'<div name="special">special 2</div>' +
'<div name="special">special 3</div>';
// Get those elements
var list = qsaWorker(target, '[name="special"]');
// Prove we got them
var p = document.createElement('p');
p.innerHTML = "Found " + list.length + " 'special' elements";
document.body.appendChild(p);
})();
</script>
</body>
</html>
Which works in IE7.
As an option for your specific scenario, where you want to get elements with a specific attribute (and value), you can use a function like this:
function getElementsByAttribute(options) {
/*if (container.querySelectorAll) {
var selector = '';
if (options.tagFilter) {
selector += options.tagFilter;
}
selector += '[' + options.attr;
if (options.val) {
selector += '="' + options.val.replace(/"/g, '\\"') + '"';
}
selector += ']';
return Array.prototype.slice.call(options.container.querySelectorAll(selector));
}*/
var elements = options.container.getElementsByTagName(options.tagFilter || "*"),
ret = [],
i, cur,
matches = (function () {
if (options.val) {
return function (el) {
return el.getAttribute(options.attr) === options.val;
};
} else {
return function (el) {
return el.hasAttribute(options.attr);
};
}
})();
for (i = 0; i < elements.length; i++) {
cur = elements[i];
if (matches(cur)) {
ret.push(cur);
}
}
return ret;
}
And you call it like:
window.onload = function () {
var contain = document.getElementById("container"),
els = getElementsByAttribute({
container: contain,
attr: "name",
val: "special",
tagFilter: ""
});
console.log("els", els);
};
DEMO: http://jsfiddle.net/cxq6t/1/
(I kept in my original logic for supporting querySelectorAll, but proved not to work in old IE with invalid attributes, per the comments)
The object you pass to the function accepts:
container: containing element to look through
attr: the attribute to look for
val: optional value to match against
tagFilter: optional filter for the tagName of matched elements
I tested in IE7/8 to see if the <div name="special"> would match, and it does. As well as the other <input />s.
If you ever wanted to expand the selector to be more complicated things like what querySelectorAll supports, you could use a polyfill like T.J.Crowder's. But this seems to get the job done.
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
var newvalue = '<img class="youtube_replace youtube_canvas" data-code="Wn-_MyJV37E" src="http://img.youtube.com/vi/Wn-_MyJV37E/0.jpg" />';
var abc = $('<div>' + newvalue + '</div>').find('*').each(function() {
}).html();
alert(abc);
</script>
I want abc to equal "newvalue". But in my current code, abc is empty. Why?
This is what I truly want to do, but for example purposes, I left this blank above:
var whitelist = ['a','div','img', 'span'];
var abc = $('<div>' + newvalue + '</div>').find('*').each(function() {
if($.inArray(this.nodeName.toLowerCase(), whitelist)==-1) {
$(this).remove();
}
}).html(); //abc is now sanitized!!!
Breaking it down:
var abc = $('<div>' + newvalue + '</div>') //Creates a div with an img element inside it
.find('*') //retrieves the img element
.each(function() {}) //iterates over the jQuery set (only one img element)
.html(); //returns the HTML serialization of the img element
//which has no contents, so it is an empty string
You could call .parent().html(), which would retrieve the contents of the div you created.
In your second example, you would want .end().html() which would pop the internal jQuery stack and get you back to the top-most div.
The issue here is that when you do:
var abc = $('<div>' + newvalue + '</div>').find('*')
your jQuery object holds the img element, not the div element. So when you're calling .html(), you're getting the inner HTML of the image - which of course doesn't exist.
var abc = $('<div>' + newvalue + '</div>')
.find('*')
.each(function() {
// stuff
})
.parent().html();
(but #Dennis got there first :). )
Do it like that (if you insist on getting HTML of element you just generated):
var abc = $('<div>' + newvalue + '</div>').html();
The problem is just incorrect mixing of different jQuery functions and callbacks.
EDIT:
The problem you have is that with find('*') you retrieve all the <img> tags (actually: one <img> tag) within <div>, but <img> tags have no HTML inside them (they have no other tags inside).
If you shorten your code to this:
var abc = $('<div>' + newvalue + '</div>').find('*').each(function() {
/* your JS code here */
}).parent().html();
you will actually receive HTML of the whole <img> tag.
jQuery: how to change tag name?
For example:
<tr>
$1
</tr>
I need
<div>
$1
</div>
Yes, I can
Create DOM element <div>
Copy tr content to div
Remove tr from dom
But can I make it directly?
PS:
$(tr).get(0).tagName = "div";
results in DOMException.
You can replace any HTML markup by using jQuery's .replaceWith() method.
example: http://jsfiddle.net/JHmaV/
Ref.: .replaceWith
If you want to keep the existing markup, you could use code like this:
$('#target').replaceWith('<newTag>' + $('#target').html() +'</newTag>')
No, it is not possible according to W3C specification: "tagName of type DOMString, readonly"
http://www.w3.org/TR/DOM-Level-2-Core/core.html
Where the DOM renameNode() Method?
Today (2014) no browser understand the new DOM3 renameNode method (see also W3C)
check if run at your bowser: http://jsfiddle.net/k2jSm/1/
So, a DOM solution is ugly and I not understand why (??) jQuery not implemented a workaround?
pure DOM algorithm
createElement(new_name)
copy all content to new element;
replace old to new by replaceChild()
is something like this,
function rename_element(node,name) {
var renamed = document.createElement(name);
foreach (node.attributes as a) {
renamed.setAttribute(a.nodeName, a.nodeValue);
}
while (node.firstChild) {
renamed.appendChild(node.firstChild);
}
return node.parentNode.replaceChild(renamed, node);
}
... wait review and jsfiddle ...
jQuery algorithm
The #ilpoldo algorithm is a good start point,
$from.replaceWith($('<'+newname+'/>').html($from.html()));
As others commented, it need a attribute copy ... wait generic ...
specific for class, preserving the attribute, see http://jsfiddle.net/cDgpS/
See also https://stackoverflow.com/a/9468280/287948
The above solutions wipe out the existing element and re-create it from scratch, destroying any event bindings on children in the process.
short answer: (loses <p/>'s attributes)
$("p").wrapInner("<div/>").children(0).unwrap();
longer answer: (copies <p/>'s attributes)
$("p").each(function (o, elt) {
var newElt = $("<div class='p'/>");
Array.prototype.slice.call(elt.attributes).forEach(function(a) {
newElt.attr(a.name, a.value);
});
$(elt).wrapInner(newElt).children(0).unwrap();
});
fiddle with nested bindings
It would be cool to copy any bindings from the at the same time, but getting current bindings didn't work for me.
To preserve the internal content of the tag you can use the accessor .html() in conjunction with .replaceWith()
forked example: http://jsfiddle.net/WVb2Q/1/
Inspired by ericP answer, formatted and converted to jQuery plugin:
$.fn.replaceWithTag = function(tagName) {
var result = [];
this.each(function() {
var newElem = $('<' + tagName + '>').get(0);
for (var i = 0; i < this.attributes.length; i++) {
newElem.setAttribute(
this.attributes[i].name, this.attributes[i].value
);
}
newElem = $(this).wrapInner(newElem).children(0).unwrap().get(0);
result.push(newElem);
});
return $(result);
};
Usage:
$('div').replaceWithTag('span')
Working pure DOM algorithm
function rename_element(node, name) {
let renamed = document.createElement(name);
Array.from(node.attributes).forEach(attr => {
renamed.setAttribute(attr.name, attr.value);
})
while (node.firstChild) {
renamed.appendChild(node.firstChild);
}
node.parentNode.replaceChild(renamed, node);
return renamed;
}
You could go a little basic. Works for me.
var oNode = document.getElementsByTagName('tr')[0];
var inHTML = oNode.innerHTML;
oNode.innerHTML = '';
var outHTML = oNode.outerHTML;
outHTML = outHTML.replace(/tr/g, 'div');
oNode.outerHTML = outHTML;
oNode.innerHTML = inHTML;
To replace the internal contents of multiple tags, each with their own original content, you have to use .replaceWith() and .html() differently:
http://jsfiddle.net/kcrca/VYxxG/
JS to change the tag name
/**
* This function replaces the DOM elements's tag name with you desire
* Example:
* replaceElem('header','ram');
* replaceElem('div.header-one','ram');
*/
function replaceElem(targetId, replaceWith){
$(targetId).each(function(){
var attributes = concatHashToString(this.attributes);
var replacingStartTag = '<' + replaceWith + attributes +'>';
var replacingEndTag = '</' + replaceWith + '>';
$(this).replaceWith(replacingStartTag + $(this).html() + replacingEndTag);
});
}
replaceElem('div','span');
/**
* This function concats the attributes of old elements
*/
function concatHashToString(hash){
var emptyStr = '';
$.each(hash, function(index){
emptyStr += ' ' + hash[index].name + '="' + hash[index].value + '"';
});
return emptyStr;
}
Related fiddle is in this link
Since replaceWith() didn't work for me on an element basis (maybe because I used it inside map()), I did it by creating a new element and copying the attributes as needed.
$items = $('select option').map(function(){
var
$source = $(this),
$copy = $('<li></li>'),
title = $source.text().replace( /this/, 'that' );
$copy
.data( 'additional_info' , $source.val() )
.text(title);
return $copy;
});
$('ul').append($items);
Take him by the word
Taken the Question by Word "how to change tag name?" I would suggest this solution:
If it makes sense or not has to be decided case by case.
My example will "rename" all a-Tags with hyperlinks for SMS with span tags. Maintaining all attributes and content:
$('a[href^="sms:"]').each(function(){
var $t=$(this);
var $new=$($t.wrap('<div>')
.parent()
.html()
.replace(/^\s*<\s*a/g,'<span')
.replace(/a\s*>\s*$/g,'span>')
).attr('href', null);
$t.unwrap().replaceWith($new);
});
As it does not make any sense to have a span tag with an href attribute I remove that too.
Doing it this way is bulletproof and compatible with all browsers that are supported by jquery.
There are other ways people try to copy all the Attributes to the new Element, but those are not compatible with all browsers.
Although I think it is quite expensive to do it this way.
Jquery plugin to make "tagName" editable :
(function($){
var $newTag = null;
$.fn.tagName = function(newTag){
this.each(function(i, el){
var $el = $(el);
$newTag = $("<" + newTag + ">");
// attributes
$.each(el.attributes, function(i, attribute){
$newTag.attr(attribute.nodeName, attribute.nodeValue);
});
// content
$newTag.html($el.html());
$el.replaceWith($newTag);
});
return $newTag;
};
})(jQuery);
See : http://jsfiddle.net/03gcnx9v/3/
Yet another script to change the node name
function switchElement() {
$element.each(function (index, oldElement) {
let $newElement = $('<' + nodeName + '/>');
_.each($element[0].attributes, function(attribute) {
$newElement.attr(attribute.name, attribute.value);
});
$element.wrapInner($newElement).children().first().unwrap();
});
}
http://jsfiddle.net/rc296owo/5/
It will copy over the attributes and inner html into a new element and then replace the old one.
$(function(){
$('#switch').bind('click', function(){
$('p').each(function(){
$(this).replaceWith($('<div/>').html($(this).html()));
});
});
});
p {
background-color: red;
}
div {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello</p>
<p>Hello2</p>
<p>Hello3</p>
<button id="switch">replace</button>
You can use this function
var renameTag = function renameTag($obj, new_tag) {
var obj = $obj.get(0);
var tag = obj.tagName.toLowerCase();
var tag_start = new RegExp('^<' + tag);
var tag_end = new RegExp('<\\/' + tag + '>$');
var new_html = obj.outerHTML.replace(tag_start, "<" + new_tag).replace(tag_end, '</' + new_tag + '>');
$obj.replaceWith(new_html);
};
ES6
const renameTag = function ($obj, new_tag) {
let obj = $obj.get(0);
let tag = obj.tagName.toLowerCase();
let tag_start = new RegExp('^<' + tag);
let tag_end = new RegExp('<\\/' + tag + '>$');
let new_html = obj.outerHTML.replace(tag_start, "<" + new_tag).replace(tag_end, '</' + new_tag + '>');
$obj.replaceWith(new_html);
};
Sample code
renameTag($(tr),'div');
Try this one also. in this example we can also have attributes of the old tag in new tag
var newName = document.querySelector('.test').outerHTML.replaceAll('h1', 'h2');
document.querySelector('.test').outerHTML = newName;
<h1 class="test">Replace H1 to H2</h1>
I am taking the value of a select element and trying to modify it so that I can have access to the onscreen preview element that the select item represents. Here is the first part of the code...
$("#single_area_select").change(function(){
var $element = '#preview_' + $("#single_area_select").val().toLowerCase();
elementChangedOrSelected($element);
});
And the critical part of the elementChangedOrSelected() method...
function elementChangedOrSelected(element){
element = '$("' + element + '")';
alert(element);
var position = element.position();
alert(position);
My first alert makes it look like i've got it right (ie, $("#preview_title") ), but the second alert doesn't make an appearance which tells me that the position query is failing. Can anyone see something that I can't?
function elementChangedOrSelected(element){
element = $(element);
alert(element);
var position = element.position();
alert("left: " + position.left + ", top: " + position.top);
}
you just need to do this:
position = $(element).position();