How can I apply some style to JavaScript's "node" object - javascript

Imagine that I have a couple of statements as following:
var n1 = oDiv.firstChild;
var n2 = oDiv.lastChild.previousSibling.firstChild; //know this crazy, but for knowledge sake
How can I apply various styles like the following (which usually works only for "element" types and not "node" types):
//does not work
n1.style.borderWidth = "1px";
n1.style.borderColor = "#336699";
n2.style.borderStyle = "solid";
Also, is there any way to typecast "node" to "element" in JavaScript?
update:
The code I am trying to accomplish above is here http://jsfiddle.net/anthachetta/4mXrd/

The DOM works exactly the same way as HTML does. That makes sense since the DOM was designed to model HTML as objects. So, what do you do if you want to make the following bold:
Hello World
From your code, what you're trying to do is something like this:
style=font-weight:bold Hello World
Obviously that wouldn't work because it's not valid HTML. What you'd normally do is this:
<span style='font-weight:bold;'>Hello World</span>
So you need to do the same in the DOM:
// Assume you have a div "div" and the first child
// is the text node "Hello World"
var hello_world = div.firstChild;
// Now, you want to make Hello World bold.
// So you need to create a span:
var span = document.createElement('span');
span.style['font-weight'] = 'bold';
// Now wrap hello_world in the span:
span.appendChild(div.removeChild(hello_world));
The above is actual working DOM code that does what you want. But beware:
Standards compliant browsers also count whitespace as nodes.
IE doesn't count whitespace as nodes.
For example, if your HTML looks like this:
<div>
<span>Hi</span>
</div>
the standard says your DOM must look like this:
div +
|---- text node (whitespace)
'---- span +
'---- text node (Hi)
but IE does what most people probably expect:
div +
'---- span +
'---- text node (Hi)
This means that you can't blindly trust node.firstChild without checking to see if it's what you expect.

There are a few problems.
What is with the lastChild.previousSibling.firstChild mess? All that's doing is confusing you.
That mess of properties is returning you a text node, not an element.
lastChild gives you "a line", previousSibling gets the <i> tag, then firstChild returns "just". You are trying to apply a style to a text node, which you can't do, you need to style an element.
You are trying to apply the style to the nodeValue. That's a string. You can use parentNode to get to the <i> tag from the text node.
oDiv.lastChild.previousSibling.firstChild.parentNode.style.color = "#FF0000";
DEMO: http://jsfiddle.net/NTICompass/4mXrd/2/

Related

How to remove content within the &lt and &gt javascript

I have a content that contains a string of elements along with images. ex:
var str= <p><img src=\"v\">fwefwefw</img></p><p><br></p><p><br></p>
the text that is within the &lt and &gt is a dirty tag and I would like to remove it along with the content that is within it. the tag is generated dynamically and hence could be any tag i.e <div>, <a>, <h1> etc....
the expected output : <p></p><p><br></p><p><br></p>
however with this code, im only able to remove the tags and not the content inside it.
str.replaceAll(/<.*?>/g, "");
it renders like this which is not what im looking for:
<p>fwefwefw</p><p><br></p><p><br></p><p><br></p>
how can I possibly remove the & tags along with the content so that I get rid of dirty tags and text inside it?
fiddle: https://jsfiddle.net/3rozjn8m/
thanks
A safe way is to use a DOM parser, visiting each text node, where then each text can be cleaned separately. This way you are certain the DOM structure is not altered; only the texts:
let str= "<p><img src=\"v\">fwefwefw</img></p><p><br></p><p><br></p>";
let doc = new DOMParser().parseFromString(str, "text/html");
let walk = doc.createTreeWalker(doc.body, 4, null, false);
let node = walk.nextNode();
while (node) {
node.nodeValue = node.nodeValue.replace(/<.*>/gs, "");
node = walk.nextNode();
}
let clean = doc.body.innerHTML;
console.log(clean);
This will also work when you have more than one <p> element that has such content.
Remove the question mark.
var str= "<p><img src=\"v\">fwefwefw</img></p><p><br></p><p><br></p>";
console.log(str.replaceAll(/<.*>/g, ""));

Spaces between elements because of new line and JavaScript createElement

I have an HTML page like this
<div id="div"></div>
I want do add there two elements (the problem appears with a and button) using JavaScript
a1 = document.createElement("a")
a1.innerText = "element1"
div.appendChild(a1)
a2 = document.createElement("a")
a2.innerText = "element2"
div.appendChild(a2)
The result is <div id="div"><a>element1</a><a>element2</a></div>.
It differs from
<div id="div">
<a>element1</a>
<a>element2</a>
</div>
The second variant has some space beetween words.
Why does this happen?
What should I do in order to get some fixed amount of space (I need it because originally worked with buttons)? What is the proper actions in this situation?
The spaced-out version has text nodes between the elements. The other version does not.
Usually, one should make sure that one's code is designed such that text nodes are completely irrelevant - whether they exist or not, the code works regardless. This is quite easy to do. Biggest thing to keep in mind that parentNode.childNodes returns a collection of all children, including text nodes, whereas parentNode.children returns a collection of only element children.
If you wanted to add text nodes like in your second code, you can pass text strings to insertAdjacentText:
const div = document.querySelector('div');
// First text node
div.insertAdjacentText('beforeend', `
`);
a1 = document.createElement("a")
a1.innerText = "element1"
div.appendChild(a1)
// Second text node
div.insertAdjacentText('beforeend', `
`);
a2 = document.createElement("a")
a2.innerText = "element2"
div.appendChild(a2)
// Third text node
div.insertAdjacentText('beforeend', `
`);
console.log('"' + div.innerHTML + '"');
<div></div>
But that's really weird. While you can do it if you really want to, it doesn't accomplish anything useful.

Creating elements within elements with javascript

Noob here. I searched on the internet a bit to find an answer to a question and I can't seem to find any (and that brings my hope down). So here I am.
I was wondering if there is a way to create an HTML element with javascript, BUT inside the newly created HTML element to create also another HTML element with javascript. I guess you can call it elementception //wink
To be more specific, I would like to create a paragraph with text, but I would like to include links in that text (or possibly buttons?).
var para = document.createElement("P");
var t = document.createTextNode("This is a paragraph. Can I do this: <a href='blabla'>like so?</a>");
para.appendChild(t);
document.body.appendChild(para);
I tried writing HTML tags inside the strings of the TextNode, but even I can see that was stupid of me. Is there a noobish(simple) way to achieve this, or any way at all? If I'm asking the impossible, please be harsh and blunt about it, so that I never ask questions again.
Thanks.
The simplest way to do this would be:
para.innerHTML = 'This is a paragraph. Here is a link: like so?';
I would use the DOM API approach instead of using innerHTML for readability, maintainability and security reasons. Sure innerHTML has been around for a long time, but just because it is easy doesn't mean you should use it for everything.
As well, if you're going to be learning JavaScript you should get acquainted with the DOM API sooner than later. It will save you a lot of headaches down the road if you get the hang of the API now.
// Create the parent and cache it in a variable.
var para = document.createElement( "p" );
// Create a text node and append it to the child.
// We don't need to cache this one because we aren't accessing it again.
para.appendChild( document.createTextNode( "This is a paragraph. Can I do this: " ) );
// Create our link element and cache it in a variable.
var link = document.createElement( "a" );
// Set the link's href attribute.
link.setAttribute( 'href', 'blabla' );
// Create a text node and append it to the link
// We don't need to cache the text node.
link.appendChild( document.createTextNode( 'like so?' ));
// Append the link to the parent.
para.appendChild( link );
// Append the parent to the body.
document.body.appendChild( para );
DOM API methods used:
Document.createElement()
Document.createTextNode()
Node.appendChild()
Element.setAttribute()
Further reading:
Document Object Model (DOM)
Element.innerHTML Security Considerations
Advantages of createElement over innerHTML?
Simply use innerHTML attribute to put HTML inside your element instead of createTexteNode, here's what you need:
var para = document.createElement("P");
para.innerHTML = "This is a paragraph. Can I do this: <a \"blabla\">like so?</a>";
document.body.appendChild(para);
Because as its name says, document.createTextNode() will only create a text and can't create HTML elements.
var para = document.createElement("P");
para.innerHTML = "This is a paragraph. Can I do this: like so?";
document.body.appendChild(para);

How to append text to a div element?

I’m using AJAX to append data to a <div> element, where I fill the <div> from JavaScript. How can I append new data to the <div> without losing the previous data found in it?
Try this:
var div = document.getElementById('divID');
div.innerHTML += 'Extra stuff';
Using appendChild:
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
var content = document.createTextNode("<YOUR_CONTENT>");
theDiv.appendChild(content);
Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by #BiAiB. So use caution if you are planning to use this version.
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.innerHTML += "<YOUR_CONTENT>";
Beware of innerHTML, you sort of lose something when you use it:
theDiv.innerHTML += 'content';
Is equivalent to:
theDiv.innerHTML = theDiv.innerHTML + 'content';
Which will destroy all nodes inside your div and recreate new ones. All references and listeners to elements inside it will be lost.
If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):
var newNode = document.createElement('div');
newNode.innerHTML = data;
theDiv.appendChild(newNode);
If you want to do it fast and don't want to lose references and listeners use: .insertAdjacentHTML();
"It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation."
Supported on all mainline browsers (IE6+, FF8+,All Others and Mobile): http://caniuse.com/#feat=insertadjacenthtml
Example from https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
If you are using jQuery you can use $('#mydiv').append('html content') and it will keep the existing content.
http://api.jquery.com/append/
IE9+ (Vista+) solution, without creating new text nodes:
var div = document.getElementById("divID");
div.textContent += data + " ";
However, this didn't quite do the trick for me since I needed a new line after each message, so my DIV turned into a styled UL with this code:
var li = document.createElement("li");
var text = document.createTextNode(data);
li.appendChild(text);
ul.appendChild(li);
From https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent :
Differences from innerHTML
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
Even this will work:
var div = document.getElementById('divID');
div.innerHTML += 'Text to append';
An option that I think is better than any of the ones mentioned so far is Element.insertAdjacentText().
// Example listener on a child element
// Included in this snippet to show that the listener does not get corrupted
document.querySelector('button').addEventListener('click', () => {
console.log('click');
});
// to actually insert the text:
document.querySelector('div').insertAdjacentText('beforeend', 'more text');
<div>
<button>click</button>
</div>
Advantages to this approach include:
Does not modify the existing nodes in the DOM; does not corrupt event listeners
Inserts text, not HTML (Best to only use .insertAdjacentHTML when deliberately inserting HTML - using it unnecessarily is less semantically appropriate and can increase the risk of XSS)
Flexible; the first argument to .insertAdjacentText may be beforebegin, beforeend, afterbegin, afterend, depending on where you'd like the text to be inserted
you can use jQuery. which make it very simple.
just download the jQuery file add jQuery into your HTML
or you can user online link:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
and try this:
$("#divID").append(data);
The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData MDN Reference AppendData
let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;
if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
lastChild.appendData("YOUR TEXT CONTENT");
java script
document.getElementById("divID").html("this text will be added to div");
jquery
$("#divID").html("this text will be added to div");
Use .html() without any arguments to see that you have entered.
You can use the browser console to quickly test these functions before using them in your code.
Why not just use setAttribute ?
thisDiv.setAttribute('attrName','data you wish to append');
Then you can get this data by :
thisDiv.attrName;

How to insert HTML string in between two DOM nodes?

Consider following DOM fragment:
<div id="div-1">foo</div>
<div id="div-2">bar</div>
Is it possible to insert HTML string (EDIT: that contains tags to render) between divs without wrapping it in another div (EDIT: or some other tag) created via document.createElement and setting its innerHTML property?
Most browsers support element#insertAdjacentHTML(), which finally became standard in the HTML5 specification. Unfortunately, Firefox 7 and lower don't support it, but I managed to find a workaround that uses ranges to insert the HTML. I've adapted it below to work for your scenario:
var el = document.getElementById("div-2"),
html = "<span>Some HTML <b>here</b></span>";
// Internet Explorer, Opera, Chrome, Firefox 8+ and Safari
if (el.insertAdjacentHTML)
el.insertAdjacentHTML ("beforebegin", html);
else {
var range = document.createRange();
var frag = range.createContextualFragment(html);
el.parentNode.insertBefore(frag, el);
}
Live example: http://jsfiddle.net/AndyE/jARTf/
This does it for straight text, which is how I read your original question (see below for an update for strings that include tags):
var div = document.getElementById('div-2');
var textNode = document.createTextNode('your text');
div.parentNode.insertBefore(textNode, div);
Live example
If you start with:
<div id="div-1">foo</div>div id="div-2">bar</div>
(note that there's no whitespace between them) then the result of the above is exactly what you would get with this HTML:
<div id="div-1">foo</div>your text<div id="div-2">bar</div>
If you really have that whitespace between the divs, you'll already have a text node there and the above will insert another one next to it. For virtually all intents and purposes, that doesn't matter, but if that bothers you, you can append to the existing text node instead if you like:
var text = 'your text';
var div = document.getElementById('div-2');
var prev = div.previousSibling;
if (prev && prev.nodeType == 3) { // 3 == TEXT_NODE
// Prev is a text node, append to it
prev.nodeValue = prev.nodeValue + text;
}
else {
// Prev isn't a text node, insert one
var textNode = document.createTextNode(text);
div.parentNode.insertBefore(textNode, div);
}
Live example
Links to W3C docs: insertBefore, createTextNode
Including HTML tags
In your revised question you've said you want to include tags to be interpreted in doing all this. It's possible, but it's roundabout. First you put the HTML string into an element, then you move the stuff over, like this:
var text, div, tempdiv, node, next, parent;
// The text
text = 'your text <em>with</em> <strong>tags</strong> in it';
// Get the element to insert in front of, and its parent
div = document.getElementById('div-2');
parent = div.parentNode;
// Create a temporary container and render the HTML to it
tempdiv = document.createElement('div');
tempdiv.innerHTML = text;
// Walk through the children of the container, moving them
// to the desired target. Note that we have to be sure to
// grab the node's next sibling *before* we move it, because
// these things are live and when we moev it, well, the next
// sibling will become div-2!
node = tempdiv.firstChild;
next = node.nextSibling;
while (node) {
parent.insertBefore(node, div);
node = next;
next = node ? node.nextSibling : undefined;
}
Live example
But here there be dragons, you have to select the container element as appropriate to the content you're inserting. For instance, we couldn't use a <tr> in your text with the code above because we're inserting it into a div, not a tbody, and so that's invalid and the results are implementation-specific. These sorts of complexities are why we have libraries to help us out. You've asked for a raw DOM answer and that's what the above is, but I really would check out jQuery, Closure, Prototype, YUI, or any of several others. They'll smooth a lot of stuff over for you.
var neuB = document.createElement("b");
var neuBText = document.createTextNode("mit fettem Text ");
neuB.appendChild(neuBText);
document.getElementById("derText").insertBefore(neuB, document.getElementById("derKursiveText"));
You search for: insertBefore
Using jquery it is very simple:
$("#div-1").after("Other tag here!!!");
See: jquery.after
It is obvious that javascript is not a pure javascript solution.

Categories