var $document = $(document);
var selector = '[data-rangeslider]';
var $element = $(selector);
// For ie8 support
var textContent = ('textContent' in document) ? 'textContent' : 'innerText';
// Example functionality to demonstrate a value feedback
function valueOutput(element) {
var value = element.value;
var output = element.parentNode.getElementsByTagName('output')[0] || element.parentNode.parentNode.getElementsByTagName('output')[0];
output[textContent] = value + 'mm';
}
$document.on('input', 'input[type="range"], ' + selector, function(e) {
valueOutput(e.target);
});
in the line output[textContent] = value + 'mm'; I need the output as value + '<span class="classname">mm</span>'
I tried most of the things and did a lot of research but no luck so far.
This might be something very simple but I am too new to JavaScript so couldn't figure it out.
You should change this line:
output[textContent] = value + 'mm';
to:
output.innerHTML = value + '<span>mm</span>';
Also, you could remove the IE8 fallback, as it will not be necessary. All browsers have support for innerHTML.
In your code you are assigning the node text and not the node HTML as you should.
You can read more about the difference between innerText and innerHTML here.
var textContent = ('textContent' in document) ? 'textContent' : 'innerText';
textContent and innerText are both functions for adding text to an element you want to use innerHTML to add HTML.
Like this:
ouput.innerHTML = ...;
Did you try this solution?
output.innerHTML = `${value} <span class="my-class">mm</span>`;
Related
I am making a program in which I want to add an input field to a table cell.
Look at the code below:
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
var newl = document.createElement("input");
newl.id = 'edit_text';
var newf = "td_" + arr_title[title];
newf.appendChild(newl);
}
newf gets the value of td_song,td_artist etc and these are already defined as:
var td_song = document.createElement("td");
var td_artist = document.createElement("td");
var td_genre = document.createElement("td");
in the same function and then I've appended them to a table and it works fine
but when I am creating the input element then there's an error:
Uncaught TypeError: newf.appendChild is not a function
I know it has no end tag and it needs to be in a form element, but the error is same when I try to add any other element.
Help!
the value stored in newf is a string, not a DOM element; appendChild is not a valid method on strings. Just because the string value stored in newf matches the name of a variable you created (td_song, etc), does not mean it is now a handle to that element. You would be better of storing your created elements in an object, keyed off of that value:
var elems = {
td_song: document.createElement("td"),
td_artist: document.createElement("td"),
td_genre: document.createElement("td")
};
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
var newl = document.createElement("input");
newl.id = 'edit_text';
var newf = "td_" + arr_title[title];
elems[newf].appendChild(newl);
}
After this line, the contents of newf is simply a string reading "td_song" for example.
var newf = "td_" + arr_title[title];
You are probably getting a JS error of "newf is not a function" ?
If you want newf to really be the one of those vars, you could explore using eval()
var newf = eval("td_" + arr_title[title]);
Does the <td> you're trying to append to have an ID of "td_" + arr_title[title]?
If so, you need to do...
var newf = document.getElementById("td_" + arr_title[title]);
newf.appendChild(newl);
newf is a string and you can't append child to string, if you want to refer to the variable with this name you should use window :
window[newf].appendChild(newl);
Hope this helps.
I am currently working on some IE11 compatibility issues. The code is fully functional in compatibility mode as it was previously optimize last for IE5.
The affected code is as follows:
/*
* This function sets the specified button state in the repair processing form
*/
function setOperationButton(buttonId, disabledState, sourceImage, styleCursor)
{
var buttonElement = document.frmRepairProcessing.elements[buttonId];
var sourceRoot = '<%=helper.getApplicationURL()%>' + '/zimages/' + '<%=localeString%>' + '/';
buttonElement.disabled = disabledState;
buttonElement.src = sourceRoot + sourceImage;
buttonElement.style.cursor = styleCursor;
}
So I am thinking the code simply needs to be updated to use getElementById, but I am not quite sure how to implement the specific form.
Please note: I have also tried document.forms().elements() and using .value as well.
I believe it will be acceptable to use below code to obtain buttonElement:
function setOperationButton(buttonId, disabledState, sourceImage, styleCursor)
{
var buttonElement = document.getElementById(buttonId);
var sourceRoot = '<%=helper.getApplicationURL()%>' + '/zimages/' + '<%=localeString%>' + '/';
buttonElement.disabled = disabledState;
buttonElement.src = sourceRoot + sourceImage;
buttonElement.style.cursor = styleCursor;
}
How do you convert a jQuery object into a string?
I assume you're asking for the full HTML string. If that's the case, something like this will do the trick:
$('<div>').append($('#item-of-interest').clone()).html();
This is explained in more depth here, but essentially you make a new node to wrap the item of interest, do the manipulations, remove it, and grab the HTML.
If you're just after a string representation, then go with new String(obj).
Update
I wrote the original answer in 2009. As of 2014, most major browsers now support outerHTML as a native property (see, for example, Firefox and Internet Explorer), so you can do:
$('#item-of-interest').prop('outerHTML');
With jQuery 1.6, this seems to be a more elegant solution:
$('#element-of-interest').prop('outerHTML');
Just use .get(0) to grab the native element, and get its outerHTML property:
var $elem = $('Some element');
console.log("HTML is: " + $elem.get(0).outerHTML);
Can you be a little more specific? If you're trying to get the HTML inside of a tag you can do something like this:
HTML snippet:
<p><b>This is some text</b></p>
jQuery:
var txt = $('p').html(); // Value of text is <b>This is some text</b>
The best way to find out what properties and methods are available to an HTML node (object) is to do something like:
console.log($("#my-node"));
From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output:
var node = $("#my-node").outerHTML;
jQuery is up in here, so:
jQuery.fn.goodOLauterHTML= function() {
return $('<a></a>').append( this.clone() ).html();
}
Return all that HTML stuff:
$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all
This seems to work fine for me:
$("#id")[0].outerHTML
The accepted answer doesn't cover text nodes (undefined is printed out).
This code snippet solves it:
var htmlElements = $('<p>google</p>↵↵<p>bing</p>'),
htmlString = '';
htmlElements.each(function () {
var element = $(this).get(0);
if (element.nodeType === Node.ELEMENT_NODE) {
htmlString += element.outerHTML;
}
else if (element.nodeType === Node.TEXT_NODE) {
htmlString += element.nodeValue;
}
});
alert('String html: ' + htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
No need to clone and add to the DOM to use .html(), you can do:
$('#item-of-interest').wrap('<div></div>').html()
It may be possible to use the jQuery.makeArray(obj) utility function:
var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];
If you want to stringify an HTML element in order to pass it somewhere and parse it back to an element try by creating a unique query for the element:
// 'e' is a circular object that can't be stringify
var e = document.getElementById('MyElement')
// now 'e_str' is a unique query for this element that can be stringify
var e_str = e.tagName
+ ( e.id != "" ? "#" + e.id : "")
+ ( e.className != "" ? "." + e.className.replace(' ','.') : "");
//now you can stringify your element to JSON string
var e_json = JSON.stringify({
'element': e_str
})
than
//parse it back to an object
var obj = JSON.parse( e_json )
//finally connect the 'obj.element' varible to it's element
obj.element = document.querySelector( obj.element )
//now the 'obj.element' is the actual element and you can click it for example:
obj.element.click();
new String(myobj)
If you want to serialize the whole object to string, use JSON.
Hi I am using jquery to get the html content of a div, remove the strong tags and then update the div with the new contents though. It isn't working for some reason though. Here is my code:
var content = $('#mydivid').html();
content = content.replace('<strong>', '').replace('</strong>', '');
$('#mydivid').html(content);
Anyone know why this isnt working?
First put in an alert to check content...
alert(content);
if that works then I would def not use replaceWith, try...
$('#mydivid').html(content);
first:
you don't need to replace twice, the first argument of replace() is regex, so you can :
content.replace(/<\/?strong>/g, "");
to remove all the <strong> and </strong> label.
second:
replaceWith() is not what you want, html() is your target.
and this is all you want:
$(function() {
$("#mydivid").html(function() {
return $(this).html().replace(/<\/?strong>/g, "");
});
});
jsfiddle: http://jsfiddle.net/pS5Xp/
the only issue I can see with the code is that you are replacing the div iteself. You probably want to do this instead:-
var content = $('#mydivid').html();
content = content.replace('<strong>', '').replace('</strong>', '');
$('#mydivid').html(content);
Also make sure you have lower case strong tags.
Sample: http://jsfiddle.net/8pVdw/
var content = $('#mydivid').html();
$('#mydivid').html(content.replace('<strong>', '').replace('</strong>', ''));
Should work.
If it doesn't, just alert the contents and see if it works.
You could try:
var div = $('#mydivid');
var strong = div.find("strong");
strong.replaceWith(strong.text());
What this does is just finds the <strong> tag and replaces it with the text contents.
A fiddle here: http://jsfiddle.net/cWpUK/1/
/**
* Syntax:
* Node replaceNode(Node newNode, Node oldNode)
* Node replaceNode(String newNode, Node oldNode)
* Node replaceNode(Object newNode, Node oldNode)
* - newNode: { String localName [, String namespaceURI ] }
* null replaceNode(null newNode, Node oldNode)
* - will delete the old node and move all childNodes to the parentNode
**/
// nodes from another document has to be imported first
// should throw an Error if newNode is descendant-or-self
// type of newNode is tested by 'firstChild' (DOM 1)
// returns new Node
var replaceNode = (function() {
var replaceNode = function(newNode, oldNode) {
var document = oldNode.ownerDocument;
if(newNode === null)
newNode = document.createDocumentFragment();
else if(typeof newNode === 'string' || newNode instanceof String)
newNode = {localName: newNode};
if(!('firstChild' in newNode)) {
var namespaceURI = 'namespaceURI' in newNode ?
newNode.namespaceURI : replaceNode.namespaceURI;
newNode = namespaceURI === null ?
document.createElement(newNode.localName) :
document.createElementNS(namespaceURI, newNode.localName);
}
var parentNode = oldNode.parentNode,
nextSibling = oldNode.nextSibling;
parentNode.removeChild(oldNode);
if(newNode.nodeType === 1 || newNode.nodeType === 11)
while(oldNode.firstChild)
newNode.appendChild(oldNode.firstChild);
parentNode.insertBefore(newNode, nextSibling);
return newNode.nodeType === 11 ? null : newNode;
};
replaceNode.namespaceURI = null;
return replaceNode;
})();
This will replace a Node with another one. This has the advantage that no EventListeners on subsequent Nodes are destroyed.
var nodeList = document.getElementById('mydivid').getElementsByTagName('strong');
while(nodeList.length)
replaceNode(null, nodeList[ nodeList.length - 1 ]);
Testcase
You probably don't want to use replaceWith. You should update the div with the new content by calling .html() again:
var content = $('#mydivid').html();
content = content.replace('<strong>', '').replace('</strong>', '');
$('#mydivid').html(content);
Works fine when I test it - http://jsbin.com/ihokav/edit#preview
A nicer alternative is to use replaceWith on the strong tags themselves:
$('#mydivid strong').replaceWith(function() { return $(this).html(); });
http://jsbin.com/ihokav/2/edit
What I would like to be able to do is create a string from a Javascript HTMLElement Object. For example:
var day = document.createElement("div");
day.className = "day";
day.textContent = "Random Text";
Now we have create the day HTMLDivElement Object is it possible to make it print as a string? e.g.
<div class="day">Random Text</div>
Variant on Gump's wrapper, since his implementation lifts the target node out of the document.
function nodeToString ( node ) {
var tmpNode = document.createElement( "div" );
tmpNode.appendChild( node.cloneNode( true ) );
var str = tmpNode.innerHTML;
tmpNode = node = null; // prevent memory leaks in IE
return str;
}
To print the resulting string on screen (re: escaped)
var escapedStr = nodeToString( node ).replace( "<" , "<" ).replace( ">" , ">");
outputNode.innerHTML += escapedStr;
Note, attributes like "class" , "id" , etc being stringified properly is questionable.
You can use this function (taken from pure.js)
function outerHTML(node){
return node.outerHTML || new XMLSerializer().serializeToString(node);
}
A few years have passed since the last answers. So here is an easier approach:
I found out that .outerHTML is supported by all major browsers now (see caniuse).
You can use it to get the HTML of an JS element with ease:
// Create a sample HTMLDivElement
var Day = document.createElement("div");
Day.className = "day";
Day.textContent = "Random Text";
// Log the element's HTML to the console
console.log(Day.outerHTML)
This will log: <div class="day">Random Text</div>
You can wrap that element into another element and use innerHTML on it:
var wrapper = document.createElement("div");
wrapper.appendChild(day);
var str = wrapper.innerHTML;
You need to create text node to add text for your created element like this:
var day = document.createElement("div");
day.className = "day";
// create text node
var txt = document.createTextNode('Random Text');
// add text to div now
day.appendChild(txt);
// append to body
document.body.appendChild(day);
Why would you use createElement if you can also directly parse a string?
Like: var string = '<div class="' + class + '">' + text + '</div>';
My element was a object with element : HTMLDivElement, so this worked for me.
console.log(row.element.outerHTML);
If you have just HTMLDivElement, then this should work:
console.log(row.outerHTML);
Simple use the function outerHTML
var anc = document.createElement("a");
anc.href = "https://developer.mozilla.org?a=b&c=d";
console.log(anc.outerHTML); // output: "<a href='https://developer.mozilla.org?a=b&c=d'></a>"
know more