Dynamically replace HTML element in UIWebView - javascript

I have some HTML loaded in WebView like this:
<html><head></head><body>before <myTag>Content</myTag> after</body></html>
I want to replace element myTag with custom text so it should look like:
<html><head></head><body>before ____MY_CUSTOM_TEXT___ after</body></html>
Also I can't change initial HTML.
How I can do this with JavaScript?
My not finished code:
var elements = document.getElementsByTagName( 'myTag' );
var firstElement = elements[0];
var parentElement = firstElement.parentNode;
var html = parentElement.innerHTML;
parentElement.innerHTML = html.replace(?????, '____MY_CUSTOM_TEXT___');
I don't know how to get string value of element to replace (?????).

Here you go:
var txt = document.createTextNode('____MY_CUSTOM_TEXT___');
parentElement.replaceChild(txt, firstElement);

Related

how to show html when using appendChild

I'm creating some elements through this code in JavaScript:
var tdiv = document.createElement("div");
tdiv.setAttribute('id', 'titlediv');
var ddiv = document.createElement("div");
ddiv.setAttribute('id', 'datediv');
var cdiv = document.createElement("div");
cdiv.setAttribute('id', 'contentdiv');
Now I have to append some html text to cdiv. I tried to do cdiv.appendChild() but it displays an error since it is not a node. Tried doing var newsupdate_ = document.createTextNode(global[j].content) then appending it but it looks like this:
Can I do setAttribute to place the content inside the desired div?
appendChild() would not work in cdiv because there is no such method present in the element created by createElement().
createTextNode() creates a new Text node. It will not evaluate any HTML present in the parameter string.
Try innerHTML like the following way:
var cdiv = document.createElement("div");
cdiv.setAttribute('id', 'contentdiv');
cdiv.innerHTML = '<h1>Header 1</h1>';
document.getElementById('container').append(cdiv);
<div id="container"></div>
use innerHTML, example
document.getElementById("demo").innerHTML = "Paragraph changed!";

Get a string and replace a div with a new one

In jquery, I have got the html of a particular div on the page and using it as a string. However please can you tell me how I can remove each class in the string called "video-js" and replace it with another div? I am trying to get a few values off each "video-js" div before replacing it with the new div with those values.
This is what I have so far, but it's not writing back to the string.
var getTheCurrentResults = $(".titanLoaderControlList").html();
var obj=$(getTheCurrentResults);
$('.video-js',obj).each(function(){
var theID = $(this).attr("id");
var videoSRC = $(this).find(".vjs-tech").attr("src");
var posterSRC = $(this).find(".vjs-tech").attr("poster");
$(this).text("<div class='playButtonContainer'><div class='playButton'><div class='playButtonSymbol'></div></div></div><div class='videoInfo' data-video-id='"+theID+"' data-source-video='"+videoSRC+"'><img class='posterInfo' src='"+posterSRC+"'></div>");
});
You should be using .html() to replace the HTML content, not .text().
var getTheCurrentResults = $(".titanLoaderControlList").html();
var obj=$(getTheCurrentResults);
$('.video-js',obj).each(function(){
var theID = $(this).attr("id");
var videoSRC = $(this).find(".vjs-tech").attr("src");
var posterSRC = $(this).find(".vjs-tech").attr("poster");
$(this).html("<div class='playButtonContainer'><div class='playButton'><div class='playButtonSymbol'></div></div></div><div class='videoInfo' data-video-id='"+theID+"' data-source-video='"+videoSRC+"'><img class='posterInfo' src='"+posterSRC+"'></div>");
});

Parse a string in jquery, change something and get the modified string back

I have a string containing html code, something like this: http://jsbin.com/ocoteg/1.
I want to parse this string, make some changes (just for example: change all links to a span), and then get the modified html string back.
Here is a jsbin, where I started this, but I can't make it work: http://jsbin.com/okireb/1/edit.
I get the html string, I parse it with jquery, but I can't replace the links, and get the modified html string back.
UPDATE
Why the downvote? What is the problem with this question?
You can do it in a loop also
dom.each(function(i,v){
if(v.tagName == "A"){
dom[i] = $('<span/>').html($(v).html())[0]; // replace it right away with new span element
}
});
var newString = $('<div>').append(dom.clone()).html(); //<-- to get new string http://stackoverflow.com/a/652771/1385672
console.log(newString);​
EDIT:
Here's how you can do it keeping the other tags
var dom = $(text.split('\n'));
$(dom).each(function(i,v){
var ele = $(v)[0];
if($(ele).is('a')){
dom[i] = $('<div>').append($('<span/>').html($(v).html())).html();
}
});
var newString = dom.get().join('\n');
http://jsbin.com/okireb/32/edit
Use find instead of filter :
var dom = $('<div>'+text+'</div>');
dom.find('a').each(function() {
var el = $(this);
var html = el.html();
var span = $('<span/>').html(html);
el.replaceWith(span);
});
console.log(dom.children()); ​
Note that I wrap everything for the case where the initial dom isn't one element.
Demonstration
To get the html back as a string use
var html = dom.html();
This should be what you want (can be improved)
var text = '<!DOCTYPE html><html><head><meta charset=utf-8 /><title>JS Bin</title></head><body>Link 1Link 2Link 3</body></html>';
var body_content = text.substring(text.indexOf('<body>') + 6, text.indexOf('</body>'));
var $dom = $('<div/>').html(body_content);
$('a', $dom).each(function() {
$('<span>' + $(this).html() + '</span>').insertAfter($(this));
$(this).remove();
});
var text_new = text.replace(body_content, $dom.html());
// text_new contains the entire HTML document with the links changed into spans
You could do it with .replace.
Probably not the nicest way of doing it though.
dom = dom.replace(/<a /g,'<span');
dom = dom.replace(/<\/a>/g,'</span>');
Demo: http://jsbin.com/okireb/14/edit

Get HTML fragment without text by jQuery

I have a HTML code with div container and another HTML element and text inside it
<div id="container"><i class="myico"></i> text</div>
I need to get only HTML element from the container without the text.
So i need to get only
<i class="myico"></i>
How can I get it using jQuery?
Simply to get the element use one of the following:
var element = $("#container > i");
var element = $("#container i");
var element = $("#container .myico");
var element = $("#container").find("i.myico");
To get the element out of the markup use detach():
var element = $("#container > i").detach();
Then to get an HTML code, you may use outerHTML property:
var html = element.get(0).outerHTML;
DEMO: http://jsfiddle.net/tLvdZ/
$('i') / $('.myico') / $('div i')... http://api.jquery.com/category/selectors/
var htmltag = $("#container").html();
htmltag = htmltag.replace($("#container").text(),"");
For reference you can use :- refer this

How to get the HTML for a DOM element in javascript

Imagine I have the following HTML:
<div><span><b>This is in bold</b></span></div>
I want to get the HTML for the div, including the div itself. Element.innerHTML only returns:
<span>...</span>
Any ideas? Thanks
Use outerHTML:
var el = document.getElementById( 'foo' );
alert( el.outerHTML );
Expanding on jldupont's answer, you could create a wrapping element on the fly:
var target = document.getElementById('myElement');
var wrap = document.createElement('div');
wrap.appendChild(target.cloneNode(true));
alert(wrap.innerHTML);
I am cloning the element to avoid having to remove and reinsert the element in the actual document. This might be expensive if the element you wish to print has a very large tree below it, though.
First, put on element that wraps the div in question, put an id attribute on the element and then use getElementById on it: once you've got the lement, just do 'e.innerHTML` to retrieve the HTML.
<div><span><b>This is in bold</b></span></div>
=>
<div id="wrap"><div><span><b>This is in bold</b></span></div></div>
and then:
var e=document.getElementById("wrap");
var content=e.innerHTML;
Note that outerHTML is not cross-browser compatible.
old question but for newcomers that come around :
document.querySelector('div').outerHTML
You'll want something like this for it to be cross browser.
function OuterHTML(element) {
var container = document.createElement("div");
container.appendChild(element.cloneNode(true));
return container.innerHTML;
}
If you want a lighter footprint, but a longer script, get the elements innerHTML and only create and clone the empty parent-
function getHTML(who,lines){
if(!who || !who.tagName) return '';
var txt, ax, str, el= document.createElement('div');
el.appendChild(who.cloneNode(false));
txt= el.innerHTML;
ax= txt.indexOf('>')+1;
str= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
el= null;
return lines? str.replace(/> *</g,'>\n<'): str;
//easier to read if elements are separated
}
var x = $('#container').get(0).outerHTML;
as outerHTML is IE only, use this function:
function getOuterHtml(node) {
var parent = node.parentNode;
var element = document.createElement(parent.tagName);
element.appendChild(node);
var html = element.innerHTML;
parent.appendChild(node);
return html;
}
creates a bogus empty element of the type parent and uses innerHTML on it and then reattaches the element back into the normal dom
define function outerHTML based on support for element.outerHTML:
var temp_container = document.createElement("div"); // empty div not added to DOM
if (temp_container.outerHTML){
var outerHTML = function(el){return el.outerHTML||el.nodeValue} // e.g. textnodes do not have outerHTML
} else { // when .outerHTML is not supported
var outerHTML = function(el){
var clone = el.cloneNode(true);
temp_container.appendChild(clone);
outerhtml = temp_container.innerHTML;
temp_container.removeChild(clone);
return outerhtml;
};
};
var el = document.getElementById('foo');
el.parentNode.innerHTML;

Categories