I encountered this "bug" in the latest verison of firefox and I don't know what causes this behavior and which is the correct result.
HTML
<div><h1 id="heading">First Title</h1></div><div><h1>Second Title</h1></div>
JavaScript
var allDivNodes = document.getElementsByTagName("div");
console.log(allDivNodes[0].childNodes);
console.log(allDivNodes[1].childNodes);
console.log(allDivNodes[0].childNodes.length);
console.log(allDivNodes[1].childNodes.length);
The result I get is the following:
And here is the quirk. If I add spaces in my HTML code and run the same script I get this result:
NEW HTML. JavaScript stays the same
<div>
<h1 id="heading">First Title</h1>
</div>
<div>
<h1>Second Title</h1>
</div>
New Result:
I thought that JavaScript was white space insensitive. So why does it change nodeLength from 1 to 3?
You could use children instead of childNodes, because of formatting you introduced some text nodes (Yes they are nodes with type 3 not just some whitespace) and childNodes will return all of them.
console.log(allDivNodes[0].children.length);
Or with childNodes you can loop though and ignore the ones with nodeType === 3.
Also similarly you have childElementCount as well which will give you the childElement count and will ignore text nodes.
I thought that JavaScript was white space insensitive. So why does it change nodeLength from 1 to 3?
Firefox is behaving correctly.
This isn't a JavaScript issue. The DOM counts "whitespace only" areas as text nodes, and so the JavaScript is correctly returning all child nodes it finds.
It was older IE that behaved differently, where such whitespace only areas would be ignored. This has been corrected since IE9.
Basically, anything that appears in the page is represented as a DOM node.
I personally prefer to compress my HTML. It not only reduces the download time, but it also makes the DOM smaller with less to occupy memory, and fewer undesired nodes to work around.
Related
I am working on a simple (I thought) word processor. It uses contenteditable. I have a list of words that I want to always appear highlighted.
<article contenteditable="true" class="content">
<p>Once upon a time, there were a couple of paragraphs. Some things were <b>bold</b>, and other things were <i>italic.</i></p>
<p>Then down here there was the word highlight. It should have a different color background.</p>
</article>
So basically what I need is a way to wrap a word in <span> tags. This has proven more difficult than I expected.
Here was what I tried first:
var text = document.querySelector('article.content').innerHTML
start = text.indexOf("highlight"),
end = start + "highlight".length;
text = text.splice(end, 0, "</span>");
text = text.splice(start, 0, "<span>");
document.querySelector('article.content').innerHTML = text;
It uses the splice method found here.
And it does exactly what I need it to do, with one big issue: the cursor gets moved. Because all the text is replaced, the cursor loses its place, which isn't a good thing for a text editor.
I've also tried a couple times using document.createRange, but the issue is that while given the start and end points of a range only includes visible characters, text.indexOf("highlight") gives the index including the tags and such.
A few ideas which I'm not sure how to execute:
Figure out where the cursor begins and place it there again after using the code above
Find the difference in indexes between createRange and indexOf
Maybe there's already a library with this kind of functionality that I just can't find
Thank you for your help!
Firstly, I would recommend against doing this by manipulating innerHTML. It's inefficient and error-prone (think of the case where the content contains an element with a class of "highlight", for example). Here's an example of doing this using DOM methods to manipulate the text nodes directly:
https://stackoverflow.com/a/10618517/96100
Maintaining the caret position can be achieved a number of ways. You could use a character offset-based approach, which has some disadvantages due to not considering line breaks implied by <br> and block elements but is relatively simple. Alternatively, you could use the selection save and restore module of my Rangy library, which may be overkill for your needs, but the same approach could be used.
Here is an example using the first approach:
http://jsbin.com/suwogaha/1
If I grab some html from one element, then attempt to assign it as the text content of another element, newlines are not preserved (at least not in the latest Firefox and Chromium).
So, for example, the follow code (with sensible html) produces output where the newlines are replaced by spaces. Well, except the alert, which works as expected.
$("#info").data("html", $("#info").html());
$("#jquery").text($("#info").data("html"));
document.getElementById("javascript").textContent = $("#info").data("html");
$("#alert").click(function() { alert($("#info").data("html")) });
Here's a running example: http://jsfiddle.net/76S7z/2/
There should be some method of setting the html of one element as the text of another while preserving newlines properly.
Is this possible with "text" or "textContent"? Is there an alternative way to do this? Is there a simple workaround? A less than simple workaround?
As you've already determined, Web browsers don't normally render newline characters \n as line breaks. If you're resistent to adding the line break element <br />, you can use the white-space CSS property with the value pre-line, which will:
Sequences of whitespace are collapsed. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.
Be sure to check the property's compatibility tables before using.
<div style="white-space: pre-line;">
Look
at
these line breaks!
</div>
Here's a JSFiddle example.
Suppose I have
<input type="hidden" id="in1">
...
<p id="editable_p"></p>
<script>
$('#some_button').click( function() {
$('#in1').val($('#editable_p').text());
});
</script>
Clearly, my intention is to set the value of the hidden field to be the content of the <p> tag. This works, however it does not maintain line breaks, which is important for me. Is there a basic library function that will copy the value of the editable paragraph that maintains the linebreaks, or is there some kind of extended hack that must be performed to get this to work as I intend?
Thanks much in advance.
You may find there are a number of text nodes in your #editable_p.p and calling text() as per a lot of XML type environments, will just concatenate the strings from the text nodes found in the descendant tree, potentially losing structure. This operation can do weird stuff to line breaks and other whitespace.
To avoid this, iterate over the actual text nodes, and concatenate the strings yourself, adding \n end of lines as necessary. Assuming you have succeeded in this and have the string with line breaks, I think talereader could be correct that a textarea or similar may be needed to represent the resulting string, and submit it faithfully to a server.
Selecting text nodes with JQuery is already outlined in
How do I select text nodes with jQuery?
I have a js replace function to replace text next to two radio buttons on a pre set form.
Script is as follows.
document.body.innerHTML=document.body.innerHTML.replace("Payment by <b>Moneybookers</b>
e-wallet<br>","");
document.body.innerHTML=document.body.innerHTML.replace("Maestro, Visa and other credit/debit cards by <b>Moneybookers</b>","Pago con Diners Club, Mastercard o Visa");}onload=x;
The script works fine in Chrome and Firefox, however, the script is not actioned in Explorer.
I believe it has something to do with there being , / - within the text I am replacing? When I use the function to replace text with no , / - in the text - it works fine in explorer, however, for example when I try to replace text.. - "Maestro, Visa and other credit/debit cards by Moneybookers" this does not work in explorer.. I'm assuming because of the coma and forward slash. Honestly I've tried everything but just can not get this to work. Any help would be greatly appreciated!!
Not sure whether it's related (I'm a Mac user without IE) but you shouldn't use multiline strings. Use \n instead.
What is returned by innerHTML varies from one browser to an other, because there is no standard about it (the content will be the same, but the way it's displayed can be different). Doing replace like that is likely to fail on some browser. You should just take an other approach to do your replace.
A better approach would be to wrap the text you want to replace with a span, this way you can more easily target the content you want to replace.
<span id="thatFirstThing">Payment by <b>Moneybookers</b>e-wallet<br></span>
An after you can do
document.getElementById("thatFirstThing").innerHTML = "";
P.S.: Doing innerHTML replace on the body also has a huge side-effect. Since you are replacing the content of your hole page. All the event handler that where bind on your page will disappear.
Edit: If you can't modify the HTML page, it's a little bit more tricky, because the DOM is not well adapted to do such thing. What you could do is to target parent element by navigating through the DOM with document.getElementById and childNodes. And once you have your parent element just write the new content you want, without doing replace.
In the end it would look something like this :
document.getElementById("someSection").childNodes[0].childNodes[1].childNodes[0].innerHTML = "";
How would I get the raw HTML of the selected content on a page using Javascript? For the sake of simplicity, I'm sticking with browsers supporting window.getSelection.
Here is an example; the content between both | represent my selection.
<p>
The <em>quick brown f|ox</em> jumps over the lazy <strong>d|og</strong>.
</p>
I can capture and alert the normalized HTML with the following Javascript.
var selectionRange = window.getSelection().getRangeAt(0);
selectionContents = selectionRange.cloneContents(),
fragmentContainer = document.createElement('div');
fragmentContainer.appendChild(selectionContents);
alert(fragmentContainer.innerHTML);
In the above example, the alerted contents would collapse the trailing elements and return the string <em>ox</em> jumps over the lazy <strong>d</strong>.
How might I return the string ox</em> jumps over the lazy <strong>d?
You would have to effectively write your own HTML serialiser.
Start at the selectionRange.startContainer/startOffset and walk the tree forwards from there until you get to endContainer/endOffset, outputting HTML markup from the nodes as you go, including open tags and attributes when you walk into an Element and close tags when you go up a parentNode.
Not much fun, especially if you are going to have to support the very different IE<9 Range model at some point...
(Note also that you won't be able to get the completely raw original HTML, because that information is gone. Only the current DOM tree is stored by the browser, and that means details like tag case, attribute order, whitespace, and omitted implicit tags will differ between the source and what you get out.)
Looking at the API's, I don't think you can extract the HTML without it being converted to a DocumentFragment, which by default will close any open tags to make it valid HTML.
See Converting Range or DocumentFragment to string for a similar Q.