JavaScript: How to replace code within element without innerHTML - javascript

I want to replace content within element in JavaScript but I cannot use innerHTML and jQuery.
For example:
<div id="MyID">
<b>Hi,</b> how are you?<br/>
I am fine.
</div>
I want to replace everything between <div id="MyID"> and </div>.
Like via innerHTML which I sadly cannot use:
document.getElementById('MyID').innerHTML = document.getElementById('MyID').innerHTML.replace(/you/, 'you');
Which will be:
<div id="MyID">
<b>Hi,</b> how are you?<br/>
I am fine.
</div>
How to do it?
I tried things like appendChild and removeChild but I still cannot figure it out.

For appendChild, you should append a dom entity

Use remove() to clear the existing content and then insertAdjacentHTML() to enter the new content. Here is your code sample as an example.
<div id="MyID">
<span id="MyID2">
<b>Hi,</b> how are you?<br/>
I am fine.
</span>
</div>
<button onclick="myFunction()">Insert a paragraph</button>
<script>
function myFunction() {
var a = document.getElementById("MyID2");
a.remove();
var b = document.getElementById("MyID");
b.insertAdjacentHTML('afterbegin', '<b>Hi,</b> how are you?<br/>I am fine.');
}
</script>

Related

Show all dropzone errors instead of one at a time [duplicate]

I have this HTML:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
</div>
and want to add more divs after the strong element to result:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
<div> ... </div>
<div> ... </div>
<div> ... </div>
</div>
I am trying this:
var row_str = '<div>content here</div>';
$('#region_North_America div:last').html(row_str);
However, there is no change to the html. This is probably so since there is no div within the element selected.
I know that the js is making it to this code because I can print the content of row_str to the console.
So, how can I get to the end of that container element to add the new items?
Thx.
Try:
$("#region_North_America").append(row_str);
using append().
Or:
$("<div>content here</div>").appendTo("#region_North_America");
To create the element on the fly, and place it in the document.
Using the appendTo method.
Your code will just place html in the last div within #region_North_America. Use the append function.
$("div.region-list").append(row_str);

Remove div and its content from html string

Lets say i have a string like this:
<div id="div1"></div>
<div class="aClass" id="div2">
<div id="div3" class="anotherClass"></div>
<div id="div4" />
</div>
<div id="div5"></div>
I want to remove div2 from the string and everything inside that div
So i got a string like this
<div id="div1"></div>
<div id="div5"></div>
I thinking something like using regex to find the first div with the id of "div2" or whatever the id of the div is and count brackets untill it gets to "< /div>". The problem is that the "div3" also got a "< /div>" at the end.
The content of the div i want to remove may contain more or less div's then this too.
Any ideas on how to code this?
Update:
var htmlText = editor3.getValue();
var jHtmlObject = jQuery(htmlText);
jHtmlObject.find("#div2").remove();
var newHtml = jHtmlObject.html();
console.log(newHtml);
Why doesn't this return anything in the console?
Update2!:
I have made a jsFiddle to make my problem visual..
http://jsfiddle.net/WGXHS/
Just put the string into jQuery and use find and then remove.
var htmlString = '<div id="div1"></div>\
<div class="aClass" id="div2">\
<div id="div3" class="anotherClass"></div>\
<div id="div4" />\
</div>\
<div id="div5"></div>';
var jHtmlObject = jQuery(htmlString);
var editor = jQuery("<p>").append(jHtmlObject);
editor.find("#div2").remove();
var newHtml = editor.html();
If you have access to jQuery and your HTML is part of the DOM you can use $.remove()
EG. $('#div2').remove();
If it's not part of the DOM, and you have it in a string, you can do something like:
$('#div2', $(myHTML)).remove();
jQuery .remove() will do
$("#div2").remove();
The regex option would work if you control generating the string so you can ensure things like order of the attributes and indentation. If not your best bet is to use an HTML parser. If you are working inside of a browser jQuery is a good option. If you are working server-side you'll need to find a parser for the language you chose.

body.innerHTML before/after nth-child

Is it possible to add something with innerHTML before/after the nth child of <body>?
e.g.:
<html>
<head></head>
<body>
<div id="first">First</div>
<div id="second">Second<div id="second_sub"></div></div>
<div id="third">Third</div>
</body>
</html>
I can add at the beginning with body.innerHTML = html + body.innerHTML and at the end with body.innerHTML += html but how to add, for example, before the second <div>?
I don't want to use replace on <div id="second"> as the source changes and the insert should be done at random. Is there a solution with innerHTML or do I need to switch to Dom Nodes? Would be slow in old browsers :(
You are probably looking for the insertBefore method. It will insert a child before the given element. Alternatively there's the appendChild method which will always push elements on the beginning of the given element.
Examples:
<body>
<span id="elem1">Hello</span>
<span id="elem2">World</span>
</body>
Let's assume we're inserting a new element stored in the var newElem:
document.insertBefore(newElem, document.getElementById("elem2")) will give:
<body>
<span id="elem1">Hello</span>
<!-- New element here! -->
<span id="elem2">World</span>
</body>
document.appendChild(newElem) will give:
<body>
<!-- New element here! -->
<span id="elem1">Hello</span>
<span id="elem2">World</span>
</body>
I'm using this by now (Thanks to ajax333221):
e = document.createElement('div');
e.innerHTML = '<div>... huge content with several sub elements ...</div>';
document.body.insertBefore(e, document.body.childNodes[2]);
This is a combination of both techniques. With this I'm able to use the fast .innerHTML without extremely blowing up the code with createElement(), setAttribute(), etc.
Other solutions are welcome.

Retrieve text from an element and insert it somewhere else

I'd like to get the text from between the "p" tags and put it in an other element, like this:
before:
<div id="Text">
<p>$1,200.00</p>
</div>
<div id="putText">
<p></p>
</div>
after:
<div id="Text">
<p>$1,200.00</p>
</div>
<div id="putText">
<p>$1,200.00</p>
</div>
Anyone know of a Javascript that can do this?
The below function copies the contents of the first paragraph under an element with ID ID to a paragraph under another element with ID putID.
function copyContents(id) {
var source = document.getElementById(id).getElementsByTagName("p")[0];
var target = document.getElementById("put" + id).getElementsByTagName("p")[0];
target.innerHTML = source.innerHTML;
}
copyContents("Text");
you can use following jQuery code
$('#putText p').html($('#Text p').html());
If you have jQuery at your disposal, it's fairly easy - something like this should work:
$('#putText>p').text($('#Text>p').text())
If you don't, then you'll have to resort to some DOM manipulation - the same stuff jQuery does behind the scenes, only you need to code it up yourself.

mootools replace the content of a div

i have the following HTML code
<div id="myDiv">
<p>content</p>
</div>
and the following JS code:
$('myDiv').set('html',htmlCode);
the problem is that the variable htmlCode is something like:
<div id="myDiv"><p>another content</p></div>
so, the result when i run the JS code is something like:
<div id="myDiv">
<div id="myDiv">
<p>another content</p>
</div>
</div>
is there a way to use "set" so that it overrides the entire div? or another solution to get something like:
<div id="myDiv">
<p>another content</p>
</div>
as the result from the JS script?
i know i could just change the variable htmlCode... i just was wondering if there's another solution to this.
Mootools offers a simple replaces method!
//new tmp element that contains the new div
var tmpDiv = new Element('div',{html:'<div id="myDiv"><p>another content</p></div>'});
//new div (first child of my tmp div) replaces the old 'myDiv' (that can be grabbed from the DOM by $)
tmpDiv.getFirst().replaces($('myDiv'));
String.implement({
replaces: function(toReplace) {
Elements.from(this).inject(toReplace, 'after');
toReplace.destroy();
}
});
'<div id="a"><p>ipsum</p></div>'.replaces($('a'));
This should do. Example: http://jsfiddle.net/UvuwG/
$('myDiv').empty();
$('myDiv').adopt(Elements.from(htmlCode).getElement('p'));
You can do
$("myDiv").getParent().set("html", htmlCode);

Categories

Resources