Add text before or after an HTML element - javascript

If i have an HTML element like <div> with some text inside or another elements can I add before or after this div some text data without an html element, just plain text?
I'd like to use only pure Javascript.
Something like :
<div id="parentDiv">
my text must be added here
<div id="childDiv"></div>
</div>

Yes, you can create a text node with document.createTextNode('the text')
Then you can insert it like an element, with appendChild or insertBefore.
Example that insert a text before #childDiv:
var text = document.createTextNode('the text');
var child = document.getElementById('childDiv');
child.parentNode.insertBefore(text, child);

Just for the record:
div.insertAdjacentHTML( 'beforeBegin', yourText );
where div is your child-DIV.
Live demo: http://jsfiddle.net/ZkzDk/

If you just need text, I find that element.insertAdjacentText(position, text) is flexible for many scenarios and is also compatible with older browsers like IE6. Where position is exactly where you want the text to be and text is the text node or just a string. The options are:
'beforebegin' Before the element itself.
'afterbegin' Just inside the element, before its first child.
'beforeend' Just inside the element, after its last child.
'afterend' After the element itself.
Like this:
let div = document.getElementById('parentDiv');
div.insertAdjacentText('afterbegin', 'My Plain Text..');

In regards to the topic and the users question for inserting before or after, here is an example for after:
var text = document.createTextNode("my text must be added here.");
var childTag = document.getElementById("childDiv");
childTag.parentNode.insertBefore(text, childTag.nextSibling);
If the childTag does not have any siblings, it is okay because the insertBefore method handles this case and simply adds it as the last child.
Also can possibly use the appendChild() method after creating text node then add your childTag via the parentNode.

You can add text node. Create node - document.createTextNode('text') and then insert/append/replace - do whatever you want.

Something like this should do it:
<script type="text/javascript">
var parent = document.getElementById('parentDiv');
var sibling = document.getElementById('childDiv');
var text = document.createTextNode('new text');
parent.insertBefore(text, sibling);
</script>

Related

TextNode or textContent?

What's the advantage of creating a TextNode and appending it to an HTML element over setting directly its textContent?
Let's say I have a span.
var span = document.getElementById('my-span');
And I want to change its text. What's the advantage of using :
var my_text = document.createTextNode('Hello!');
span.appendChild(my_text);
over
span.textContent = 'hello';
It 's not really matter of advantage but of proper usage depending on the need.
The fundamental difference is that:
createTextNode() is a method and works just as its name says: it creates an element... then you must do something with it (like in your example, where you append it as a child);
so it is useful if you want to have a new element and place it somewhere
textContent is a property you may get or set, with a unique statement and nothing else;
so it is useful when you only want to change the content of an already existing element
Now in the precise case of your question, you said you want to change the text of the element...
To be more clear say you have the following HTML element:
<span>Original text</span>
If you're using your first solution:
var my_text = document.createTextNode('Hello!');
span.appendChild(my_text);
then it will end with:
<span>Original textHello!</span>
because you appended your textNode.
So you should use the second solution.

Get text inside parent div

I'm trying to get a text from an element, which isn't the first parent of the string. i.e.
<div id="wrp">
<h1>
this is the text I want
</h1>
</div>
let's say I got the div parent by element=document.getElementById("wrap") and now I want to get it's final text without looking inside all it's children : h1 and a. just the text that I see on the site.
Is it possible? Please show me an example.
You can use both innerText or textContent, but innerText doesn't works on Firefox. So, a crossbrowser solution:
var text = element.innerText || element.textContent;
JSBin. Interesting comparision about them.
You want to chain your queries so that you get the anchor tag after you get the wrap div (assuming you will never add more divs inside the anchor tag, which would be a bit weird):
var wrap = document.getElementById("wrap");
var text = wrap.getElementsByTagName("a")[0].innerHTML;
If you take a look at the Mozilla article it has more examples on how to do this. Alternatively there is textContent but since you stated that you might add more elements at a later date, if they have text in them too then you end up needing to refactor:
var wrap = document.getElementById("wrap");
var text = document.getElementById("wrap").textContent;

Moving the content of a DIV to another DIV with jQuery

http://www.frostjedi.com/terra/scripts/demo/jquery02.html
According to this link elements can be moved around by doing $('#container1').append($('#container2')). Unfortunately, it doesn't seem to be working for me. Any ideas?
See jsfiddle http://jsfiddle.net/Tu7Nc/1/
You must append not your div exactly, but your div's content(inner HTML) with Jquery's html() function.
HTML:
<div id="1">aaa</div>
<div id="2">bbb</div>​
Jquery:
$("#1").append($("#2").html());
Result:
aaabbb
bbb
It is best not to use html().
I ran into some issues due to html interpreting the contents as a string instead of a DOM node.
Use contents instead and your other scripts should not break due to broken references.
I needed to nest the contents of a DIV into a child of itself, here is how I did it.
example:
<div id="xy">
<span>contents</span>
</div>
<script>
contents = $("#xy").contents(); //reference the contents of id xy
$("#xy").append('<div class="test-class" />'); //create div with class test-class inside id xy
$("#xy").find(">.test-class").append(contents); //find direct child of xy with class test-class and move contents to new div
</script>
[EDIT]
The previous example works but here is a cleaner and more efficient example:
<script>
var content = $("#xy").contents(); //find element
var wrapper = $('<div style="border: 1px solid #000;"/>'); //create wrapper element
content.after(wrapper); //insert wrapper after found element
wrapper.append(content); //move element into wrapper
</script>
To move contents of a div (id=container2) to another div (id=container1) with jquery.
$('#container2').contents().appendTo('#container1');
You can also do:
var el1 = document.getElementById('container1');
var el2 = document.getElementById('container2');
if (el1 && el2) el1.appendChild(el2);
or as one statement, but not nearly as robust:
document.getElementById('container1').appendChild(document.getElementById('container2'));
Edit
On reflection (several years later…) it seems the intention is to move the content of one div to another. So the following does that in plain JS:
var el1 = document.getElementById('container1');
var el2 = document.getElementById('container2');
if (el1 && el2) {
while (el2.firstChild) el1.appendChild(el2.firstChild);
}
// Remove el2 if required
el2.parentNode.removeChild(el2);
This has the benefit of retaining any dynamically added listeners on descendants of el2 that solutions using innerHTML will strip away.
$('#container1').append($('#container2').html())
Well, this one could be an alternative if you want to Append:
document.getElementById("div2").innerHTML=document.getElementById("div2").innerHTML+document.getElementById("div1").innerHTML
if you wanted to rewrite contents:
document.getElementById("div2").innerHTML=document.getElementById("div1").innerHTML
I suggest a general approach with a function and jQuery:
function MoveContent(destId, srcId) {
$('#' + destId).append($('#' + srcId).contents().detach());
}
Content of a detached source node is appended to a destination node with call:
MoveContent('dest','src');
The first parameter is an id of a new parent node (destination), the second is an id of an old parent node (source).
Please see an example at: http://jsfiddle.net/dukrjzne/3/

How to use jQuery selector/find() against text string without inserting into the DOM?

I have a text string i'm trying to select the spans from using jQuery. I'd like to grab the spans w/o adding the element to the dom -- if that's possible?
After reading the jquery docs i was under the assumption that i could create a fragment by wrapping the string in a jquery selector tag, then using.find() to find the elements i want.
I have code that is similar to this but from the looks of the last line, it's obvious that no spans are being selected; any help would be greatly appreciated:
// 'text' is normally generated automatically...
// just made it an escaped string for example purposes.
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $(text).find('span');
console.log(text); // => <span id="blah1">Y</span><br/><span id="blah2">o</span><br/>
console.log(spans.length); // => 0
Thanks.
You want to use filter(), not find()
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $(text).filter('span');
console.log(spans.length);
jsFiddle
From the jQuery docs
filter:
The supplied selector is tested against each element; all elements
matching the selector will be included in the result.
find:
the .find() method allows us to search through the descendants of
these elements in the DOM tree and construct a new jQuery object from
the matching elements.
with your html fragment, there is no wrapper element, so there is no descendants, hence why find() does not work.
You are basically doing:
var elems = jQuery("<span id=\"blah1\">Y</span>").add("<br/>").add("<span id=\"blah2\">o</span>").add("<br/>");
If you want find to work with find(), you need to wrap it in an element.
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = jQuery("<div></div>").append(text).find("span");
console.log(spans.length);
You want to use filter in this case:
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $(text).filter('span');
console.log(spans.length); // 2
Demo: http://jsfiddle.net/ambiguous/TGY3J/
Or wrap it in a <div> and use find:
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $('<div>' + text + '</div>').find('span');
console.log(spans.length); // 2
Demo: http://jsfiddle.net/ambiguous/qbCjk/
find works on descendants but without the <div> wrapper, your $(text) doesn't have any <span> descendants. Wrapping your HTML in a <div> is probably your best bet, that way you don't have to worry about how deep your desired elements are.

Javascript - div content without innerHTML

I wanted to ask how to change div content, but not using innerhtml.
DEMO: http://jsfiddle.net/Cb6ME/
// get the div
var div = document.getElementById('foo');
// remove child nodes while at least one exists
while( div.childNodes[0] ) {
div.removeChild( div.childNodes[0] );
}
// create a new span element
var span = document.createElement( 'span' );
// give it some text content
span.appendChild( document.createTextNode("I'm new!!!") );
// append the span to the original div
div.appendChild( span );
You can use nodeValue to access the value of a node, however the value of a div. In your example you might have the following HTML...
<div id="myLovelyDiv">This is the text that you want to change</div>
and this script...
var myDiv = getElementById("myLovelyDiv");
myDiv.childNodes[0].nodeValue = "The text has been changed.";
but I fail to see why you wouldn't use
myDiv.innerHTML = "The text has been changed properly.";
A DIV element is a generic block level (by default) element in HTML used as a structural container to hold one or more block or inline elements.
Depending on what it is you want to change you can either select the sub-node in question directly, loop over the childNodes property to find the desired sub-node or completely rewrite the contents as html using innerHTML (which you stated you didn't want to do).
If you want to add content you can create a new element and use the appendChild(child) method of the DIV element to add to it's contents.
Is that what you were looking for?
I know I'm late but .textContent can be replaced for .innerHTML (if you only want to change the text and not code HTML).

Categories