how to concatenate text with image in a variable - javascript

Hello first i am basic to java script i have a some on mouse over divs which every one
contains information along images. the problem is that i want to combine text with an image
inside a variable whenever i am mouse hovering each divs so the information along the image
should change as i did program for every one of them
the problem is that how to combine the text and image inside a variable
but i don't know how to do that here is the code:
<script type="text/javascript">
function ENGshowElements(){
var Engineering = "Your In Engineering Section <br> <img src='a.jpg'>";
document.getElementById("contents").innerHTML = Engineering;
}
function CONshowElements(){
var Construction = "Your In Construction Section";
document.getElementById("contents").innerHTML = Construction;
}
function LLCshowElements(){
var LLCDubia = "Your In LLC Dubia Section";
document.getElementById("contents").innerHTML = LLCDubia;
}
function WASshowElements(){
var WasteManagement = "Your In Waste Management Section";
document.getElementById("contents").innerHTML = WasteManagement;
}
function TRAshowElements(){
var Transportation = "Your In Transportation Section";
document.getElementById("contents").innerHTML = Transportation;
}
function LOGshowElements(){
var Logistics = "Your In Logistics Section";
document.getElementById("contents").innerHTML = Logistics;
}
</script>
<div class="firstbox" id="Engineering" onmouseover="ENGshowElements(); return false; " >Engineering</div>
<div class="secbox" id="Construction" onmouseover="CONshowElements(); return false; ">Construction</div>
<div class="thirdbox" id="LLCDubia" onmouseover="LLCshowElements(); return false; " >LLC Dubia</div>
<div class="fourthbox" id="WasteManagement" onmouseover="WASshowElements(); return false; " >Waste Management</div>
<div class="fivthbox" id="Transportation" onmouseover="TRAshowElements(); return false; " >Transportations</div>
<div class="sixthbox" id="Logistics" onmouseover="LOGshowElements(); return false; " >Logistics</div>

DEMO: jsFiddle
HTML:
<div class="firstbox" id="Engineering">Engineering</div>
<div class="secbox" id="Construction">Construction</div>
<div class="thirdbox" id="LLCDubia">LLC Dubia</div>
<div class="fourthbox" id="WasteManagement">Waste Management</div>
<div class="fivthbox" id="Transportation">Transportations</div>
<div class="sixthbox" id="Logistics">Logistics</div>
<div id="contents"></div>
JS:
document.getElementById('Engineering').onmouseover = ENGshowElements;
document.getElementById('Construction').onmouseover = CONshowElements;
document.getElementById('LLCDubia').onmouseover = LLCshowElements;
document.getElementById('WasteManagement').onmouseover = WASshowElements;
document.getElementById('Transportation').onmouseover = TRAshowElements;
document.getElementById('Logistics').onmouseover = LOGshowElements;
function ENGshowElements() {
var Engineering = "Your In Engineering Section <br> <img src='a.jpg'>";
document.getElementById("contents").innerHTML = Engineering;
}
function CONshowElements() {
var Construction = "Your In Construction Section";
document.getElementById("contents").innerHTML = Construction;
}
function LLCshowElements() {
var LLCDubia = "Your In LLC Dubia Section";
document.getElementById("contents").innerHTML = LLCDubia;
}
function WASshowElements() {
var WasteManagement = "Your In Waste Management Section";
document.getElementById("contents").innerHTML = WasteManagement;
}
function TRAshowElements() {
var Transportation = "Your In Transportation Section";
document.getElementById("contents").innerHTML = Transportation;
}
function LOGshowElements() {
var Logistics = "Your In Logistics Section";
document.getElementById("contents").innerHTML = Logistics;
}

=> jsfiddle http://jsfiddle.net/Gy5rH/
just for the sake of making things clear, and pointing out that you're probably going the wrong way, here is a better alternative. It could probably be done mostly using css but here's something more easier to maintain.
Instead of using multiple triggers, We will use only one click function on every button. Each button will have a "data-target" which is the id of an other element.
Our markup will look like this:
<html>
<head>
<style>
#source { display: none; }
</style>
<script>
// Our click event
function clickEvent (ev) {
// Get the target in the dom
// While checking more about event should be good because
// Target may not be the element you're looking for in some cases.
var target = ev.target.dataset['target'];
var obj = document.getElementById(target);
// change the content with the one found
document.getElementById('content').innerHTML = obj.innerHTML;
}
function loaded() {
var docs = document.getElementsByClassName("btn");
// Transform to array
docs = Array.prototype.slice.call(docs);
docs.forEach(function(elem) {
// Assign click event to all elements
elem.onclick = clickEvent;
});
}
</script>
</head>
<body onload="loaded()">
<div>
<button class="btn" data-target="Engineering-Source">Engineering</button>
...
</div>
<div id="content"></div>
<div id="source">
<div id="Engineering-Source">
Your In Engineering Section <br> <img src='a.jpg'>
</div>
...more after
</div>
</body>
</html>
I added comments, but it's a nice way to do. Avoiding "vanillajs" might not be a bad thing but. It can be done without much pain in vanillajs.
That said, here are some reasons why it's good. The content remains in the html instead of javascript. If a web spider will download your page, there are far more chances that it will look for html content instead of text in javascript source.
In my example, some things might not exists in old browser like "dataset" and "forEach".
Note
That said, a pure "css" way of doing this is possible but might make the structure of the document harder to edit. On the other hand, there are ways to mix css and js to keep a minimum of js and as much as possible html/css to keep the styles in line.
Anyway, my example above should be working in some browsers to give an idea how to do it. I recommend using libraries like jQuery or prototype if you're not familiar with Javascript yet. The code above shouldn't definitely end up in production.

Related

Remove some auto generated text from a heading with javascript

I'm using uncode theme and I have a page heading that is showing 'Archive: Portfolio'
I want to remove the 'Archive:' bit from that heading.
In the source it looks like this:
<h1 class="header-title h1"><span>Archives: Projects</span></h1>
I have tried removing Archive from all the page titles with Yoast SEO plugin but it is still showing.
Is there a way to remove that word with javascript maybe does anyone know?
Thanks!
I'd be wary in removing it via javascript. It seems to me that adding a piece of text somewhere in the code's execution, and then removing it on the client-side smells like "contrived complexity".
Take a look at the wordpress template hierarchy, and manually search for the template file that's rendering the Archives: string of text.
I'd start with archive.php, and then fall my way up through other archive-*.php pages, then to taxonomy.php category.php, and so on.
If you're comfy in the command line, you might also consider grepping for the string: grep -r /path/to/wp/theme "Archive:" and sifting through the results to find the template file(s) with that on one of their lines.
But if you insist on removing the string via javascript, you might try dropping something like this at the bottom of the <body>, via a function in functions.php:
function remove_archive_text_via_js() {
if (is_archive()) { ?>
<script type="text/javascript">
var archiveHeaders = document.getElementsByClassName('header-title');
for (i = 0, headerCount = archiveHeaders.length; i < headerCount; i++) {
var replacedText = archiveHeaders[i].textContent.replace('Archives: ', '');
archiveHeaders[i].textContent = replacedText;
}
</script>
<?php }
}
add_action('wp_footer', 'remove_archive_text_via_js');
var elem = document.getElementsByClassName('header-title h1');
var innerSpan = elem[0].getElementsByTagName('span');
innerSpan[0].innerHTML = innerSpan[0].innerHTML.replace('Archives: ', 'jsfiddle');
jsfiddle: https://jsfiddle.net/orcadj3u/
$(function() {
$( "h1 span" ).each(function( index ) {
var newtext = $(this).text().replace("Archives: ", " ");
$(this).html(newtext);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1 class="header-title h1"><span>Archives: Projects</span></h1><br>
<h1 class="header-title h1"><span>Archives: Solutions</span></h1><br>
<h1 class="header-title h1"><span>Archives: Yozgat</span></h1><br>
<h1 class="header-title h1"><span>Archives: Turkey</span></h1><br>

JavaScript Display Image and Text Rather than Alert Message

I'm a newbie and starting to learn coding. I have a question regarding the famous "How many fingers am I holding up?" project. So instead of an alert message, I want the actual image of a finger with 1-5 and the message of either it is correct or not.
I think there are jquery codes.. but i don't want to jump to jquery and learn hardcore javascript first. I'm stuck with creating image Arrays and cannot manage to make the image come up.
Here's the code I have:
<body>
<p>How many fingers am I holding up?</p>
<p><input type="text" id="guess"> <button id="checkGuess">Guess!</button></p>
<div id="image"></div>
<div id="text"></div>
<script type="text/javascript">
var imgArray = new Array();
imgArray[1] = new Image();
imgArray[1].src="images/1.png";
imgArray[2] = new Image();
imgArray[2].src="images/2.png";
imgArray[3] = new Image();
imgArray[3].src="images/3.png";
imgArray[4] = new Image();
imgArray[4].src="images/4.png";
imgArray[5] = new Image();
imgArray[5].src="images/5.png";
document.getElementById("checkGuess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
} else {
alert("Nope! The number was " + randomNumber);
}
}
</script>
</body>
Thanks Guys! Appreciate your help!
Cheers!
Char
I think you can do something like this fiddle.
https://jsfiddle.net/6a4p2po4/5/
What I did was to make the imgArray an array of src of images, and updated the img src depending on the result.
I noticed while working you have some typos and unset variables.
For example, "doument" is misspelled, and "'num'" is not set.
doument.getElementById("image").innerHTML = imgArray[num] + alert("Well done! You got it!");
It might help to use Chrome or another browser to check the console (F12). It will definitely help you debug.
Using console.log() instead of alert() will make it show up as a log instead of a pop up window, so you can check the values that you stored on variables, i.e. console.log(randomNumber);
You're on the right track! Good job so far!
You said
So instead of an alert message, I want the actual image of a finger...
which leads me to think that we never want to call alert() and instead want to display an image and a message. Assuming I am correct in my supposition, here is some code...
<html>
<head>
<!-- some other stuff... -->
<!-- CSS is your friend! -->
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<p>How many fingers am I holding up?</p>
<p>
<input type="text" id="guess">
<button id="checkGuess" onclick="checkGuess()">Guess!</button>
</p>
<div id="image">
<!-- We can put the images in here then just hide/show them, which is much easier! -->
<img class="hidden" src="./images/1.png"/>
<img class="hidden" src="./images/2.png"/>
<img class="hidden" src="./images/3.png"/>
<img class="hidden" src="./images/4.png"/>
<img class="hidden" src="./images/5.png"/>
</div>
<div id="text"></div>
<script>
function checkGuess(){
var actualFingerCount = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
//the `+` casts the value into a number
var userGuess = +document.getElementById('guess').value;
//get all of our images
var images = document.querySelectorAll('img');
//hide all of them just to be safe
images.forEach(function(img){
img.classList.add('hidden');
});
//then show the one we want
images[actualFingerCount - 1].classList.remove('hidden');
var textDiv = document.getElementById('text');
if(actualFingerCount === userGuess) {
textDiv.innerHTML = 'Yay, you got it!';
}
else {
textDiv.innerHTML = 'Whoops, try again! The number was ' + actualFingerCount + '.';
}
}
</script>
</body>
</html>
And there you have it!
Notice that this is a contrived example. In the real world, you should never define functions in the global namespace, nor should you rely on elements being in a certain order, like I did with the images. Maybe you can take it and improve it to follow better coding standards!

Create html element with jquery based on user input

So after searching a while I haven't been able to find an existing question that seems to address this in a way that I can relate to with my specific issue. If there is already a good thread on this that I missed, my apologies in advance and feel free to just post a link to it and call me a dummy!
In plain english, here's the goal: I basically want to generate some html with jquery but with a couple of twists. There will basically be two sets of content that will alternate with every other number, I'll call them content-a and content-b. The user is prompted to enter a number, let's say user enters 4. Upon submitting this value, the markup is then generated like so: (1)content-a (2)content-b (3)content-a (4)content-b.
So here's a bit of code that hopefully will help a little.
I'm aware of how to generate html, but that's about as far as I've gotten so far, my js is definitely a weak point and needs lots of practice:
$("#targetDIV").html("<h1>Hello World!</h1> <p>This is a big fat test</p>");
The markup is simple enough, almost seems pointless to post it in here since it's kind of obvious but I'll do it anyway:
<div id="targetDIV" style="border: 3px solid purple">
</div>
The desired output though would be something like this, based on the value the user chooses but let's just stick with the 4 example:
<div id="targetDIV" style="border: 3px solid purple">
<!-- Content A -->
<h1>Hello World!</h1>
<p>This is a big fat test</p>
<!-- Content B -->
<h1>Hello Universe!</h1>
<p>This is a super mega big fat test</p>
<!-- Content A -->
<h1>Hello World!</h1>
<p>This is a big fat test</p>
<!-- Content B -->
<h1>Hello Universe!</h1>
<p>This is a super mega big fat test</p>
</div>
Hopefully there's enough here to go on or to at least point me in the right direction, thanks in advance for any wisdom any of you might offer up!
Here is a full, working live example that does exactly what you're looking for.
The following code will take a numerical input from the user, then append alternating sets of content according to the number the user inputted:
var num = prompt("Enter a number");
var contenta = "<h1>Hello World!</h1> <p>This is a big fat test</p>";
var contentb = "<h1>Hello Universe!</h1> <p>This is a super mega big fat test</p>";
var targetDiv = $("#targetDIV");
console.log(targetDiv);
for (var i = 0; i < num; i++) {
if (i % 2 === 0) targetDiv.append(contenta);
else targetDiv.append(contentb);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="targetDIV" style="border: 3px solid purple">
</div>
You could assign the two html strings to the indices of an array.
var str1 = "<h1>Hello World!</h1> <p>This is a big fat test</p>"
var str2 = "<h1>Hello Universe!</h1> <p>This is a super mega big fat test</p>"
var responses = [str1, str2];
Then, you can use a for loop that will repeat as many times as the user's input.
And in each iteration of the loop, you could perhaps $('#targetDIV').append(responses[i % 2]);
You could do something like this.
$('#number').change(function() {
var ind = $(this).val()
$('#target-div').append($('#holder div').get(ind))
});
This keeps the HTML in a hidden div, then extracts your desired content by its index. Not the best way but works.
JSFiddle
If you are simply alternating between two content sets, you can simply store them as a JS array, say content, and generate/insert them on the fly.
The key is to empty your target element when the user updates the change count, and access the correct element in the array based on the modulus of the array size, i.e. content[i%content.length]. This method allows you to arbitarily increase the size of your content array, and the script will keep inserting elements by going through the list, and repeat from the start when it reaches the end.
$(function() {
var content = [
'<h1>Hello World!</h1> <p>This is a big fat test</p>',
'<h1>Hello Universe!</h1><p>This is a super mega big fat test</p>'
];
$('#count').on('change', function() {
$('#targetDIV').empty();
var count = parseInt($(this).val());
for (var i = 0; i < count; i++) {
$('#targetDIV').append(content[i%content.length]);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="count" type="number" min="0" step="1" value="0" placeholder="0" />
<div id="targetDIV" style="border: 3px solid purple"></div>
I am not an expert js dev but cooked something quick and easy for you.
link to codepen:http://codepen.io/anon/pen/OVdMow
$(function() {
var A = '<!-- Content A --><h1>Hello World!</h1><p>This is a big fat test</p>';
var B = '<!-- Content B --><h1>Hello Universe!</h1><p>This is a super mega big fat test</p>';
var targetDiv = $('#targetDIV');
$('#listCount').on('input', function() {
targetDiv.empty();
for(var i = 0; i < +this.value; i++) {
targetDiv.append( i % 2 == 0 ? A : B );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="listCount" id="listCount"/>
<div id="targetDIV" style="border: 3px solid purple">
</div>
function generateElments() {
var num = $("#numOfElements").val();
var writeA = true;
var aElement = "<p>I am <strong>A</strong>!</p>";
var bElement = "<p>I am <strong>B</strong>!</p>";
for (var i = 0; i < num; i++) {
$("#elements-container").append(writeA ? aElement : bElement);
writeA = !writeA;
};
};
Here is a working plunker of what you need!
http://plnkr.co/edit/qI1LtBwDwu7KIKFzUehB?p=preview

a more graceful multi-line javascript string method

The only way I know how to print a huge string without using += is to use \ backslashes. ugly!
<div id="foo"></div>
<script type="text/javascript">
var longString = '<div id="lol">\
<div id="otherstuff">\
test content. maybe some code\
</div>\
</div>';
document.getElementById('foo').innerHTML = longString;
</script>
is there any way to do this where the longString is untainted? php has $foo = ''' long multiline string '''; I want this in javascript!
Anyone know of a better method for printing long, multi-line strings in javascript?
In general, the answer is: not in the language syntax. Though as Ken pointed out in his answer there are many work-arounds (my personal method is to load a file via AJAX). In your specific case though, I'd prefer creating a HTML constructor function so you can then define the HTML structure using javascript object literals. Something like:
var longString = makeHTML([{
div : {
id : "lol",
children : [{
div : {
id : "otherstuff",
children : [{
text : "test content. maybe some code"
}]
}]
}]
which I find to be much easier to handle. Plus, you this would allow you to use real function literals when you need it to avoid string quoting hell:
makeHTML([{
span : {
onclick : function (event) {/* do something */}
}
}]);
note: the implementation of makeHTML is left as exercise for the reader
Additional answer:
Found some old code after a quick scan through my hard disk. It's a bit different from what I suggested above so I thought I'd share it to illustrate one of the many ways you can write functions like this. Javascript is a very flexible language and there is not much that forces you to write code one way or another. Choose the API you feel most natural and comfortable and write code to implement it.
Here's the code:
function makeElement (tag, spec, children) {
var el = document.createElement(tag);
for (var n in spec) {
if (n == 'style') {
setStyle(el,spec[n]);
}
else {
el[n] = spec[n];
}
}
if (children && children.length) {
for (var i=0; i<children.length; i++) {
el.appendChild(children[i]);
}
}
return el;
}
/* implementation of setStyle is
* left as exercise for the reader
*/
Using it would be something like:
document.getElementById('foo').appendChild(
makeElement(div,{id:"lol"},[
makeElement(div,{id:"otherstuff"},[
makeText("test content. maybe some code")
])
])
);
/* implementation of makeText is
* left as exercise for the reader
*/
One technique if you have a big block is a <script> tag with an invalid type. It will be ignored by browsers.
<script type="text/x-my-stuff" id="longString">
<div id="lol">
<div id="otherstuff">
test content. maybe some code
</div>
</div>
</script>
<script type="text/javascript">
var longString = document.getElementById("longString").text;
document.getElementById('foo').innerHTML = longString;
</script>
A few somewhat unattractive options are discussed in the answers to this question.
You really could minimize this ugliness by creating your <div id="lol"> as HTML, and set its content with .innerHTML = "test content. maybe some code"
I don't like creating HTML in Javascript because of this exact issue, and instead use "template" elements which i simply clone then manipulate.
var lol = document.getElementById("template_lol").clone();
lol.firstChild.innerHTML = "code and stuff";
foo.appendChild(lol);
And this is the HTML:
<body>
<div>normal stuff</div>
<div style="display:none" id="templateBucket">
<div id="template_lol"><div class="otherstuff"></div></div>
</div>
</body>
This works too :
var longString =
'<div id="lol">' +
'<div id="otherstuff">' +
'test content. maybe some code' +
'</div>' +
'</div>';

Finding out what line number an element in the dom occurs on in Javascript?

Though I've never heard of this but, is it possible to retrieve a node from the DOM using JS, and then find out on what line of the file that node occurred on?
I'm open to anything, alternative browsers plugins/add-ons etc...it doesn't need to be cross-browser per say.
I would assume that this would be possible somehow considering that some JS debuggers are capable of finding the line number within a script tag, but I'm not entirely sure.
Ok, forgive me for how large this is. I thought this was a very interesting question but while playing with it, I quickly realized that innerHTML and its ilk are quite unreliable wrt maintaining whitespace, comments, etc. With that in mind, I fell back to actually pulling down a full copy of the source so that I could be absolutely sure I got the full source. I then used jquery and a few (relatively small) regexes to find the location of each node. It seems to work well although I'm sure I've missed some edge cases. And, yeah, yeah, regexes and two problems, blah blah blah.
Edit: As an exercise in building jquery plugins, I've modified my code to function reasonably well as a standalone plugin with an example similar to the html found below (which I will leave here for posterity). I've tried to make the code slightly more robust (such as now handling tags inside quoted strings, such as onclick), but the biggest remaining bug is that it can't account for any modifications to the page, such as appending elements. I would need probably need to use an iframe instead of an ajax call to handle that case.
<html>
<head id="node0">
<!-- first comment -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style id="node1">
/* div { border: 1px solid black; } */
pre { border: 1px solid black; }
</style>
<!-- second comment -->
<script>
$(function() {
// fetch and display source
var source;
$.ajax({
url: location.href,
type: 'get',
dataType: 'text',
success: function(data) {
source = data;
var lines = data.split(/\r?\n/);
var html = $.map(lines, function(line, i) {
return ['<span id="line_number_', i, '"><strong>', i, ':</strong> ', line.replace(/</g, '<').replace(/>/g, '>'), '</span>'].join('');
}).join('\n');
// now sanitize the raw html so you don't get false hits in code or comments
var inside = false;
var tag = '';
var closing = {
xmp: '<\\/\\s*xmp\\s*>',
script: '<\\/\\s*script\\s*>',
'!--': '-->'
};
var clean_source = $.map(lines, function(line) {
if (inside && line.match(closing[tag])) {
var re = new RegExp('.*(' + closing[tag] + ')', 'i');
line = line.replace(re, "$1");
inside = false;
} else if (inside) {
line = '';
}
if (line.match(/<(script|!--)/)) {
tag = RegExp.$1;
line = line.replace(/<(script|xmp|!--)[^>]*.*(<(\/(script|xmp)|--)?>)/i, "<$1>$2");
var re = new RegExp(closing[tag], 'i');
inside = ! (re).test(line);
}
return line;
});
// nodes we're looking for
var nodes = $.map([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(num) { return $('#node' + num) });
// now find each desired node in both the DOM and the source
var line_numbers = $.map(nodes, function(node) {
var tag = node.attr('tagName');
var tags = $(tag);
var index = tags.index(node) + 1;
var count = 0;
for (var i = 0; i < clean_source.length; i++) {
var re = new RegExp('<' + tag, 'gi');
var matches = clean_source[i].match(re);
if (matches && matches.length) {
count += matches.length;
if (count >= index) {
console.debug(node, tag, index, count, i);
return i;
}
}
}
return count;
});
// saved till end to avoid affecting source html
$('#source_pretty').html(html);
$('#source_raw').text(source);
$('#source_clean').text(clean_source.join('\n'));
$.each(line_numbers, function() { $('#line_number_' + this).css('background-color', 'orange'); });
},
});
var false_matches = [
"<div>",
"<div>",
"</div>",
"</div>"
].join('');
});
</script>
</head>
<!-- third comment -->
<body id="node2">
<div>
<pre id="source_pretty">
</pre>
<pre id="source_raw">
</pre>
<pre id="source_clean">
</pre>
</div>
<div id="node3">
<xmp>
<code>
// <xmp> is deprecated, you should put it in <code> instead
</code>
</xmp>
</div>
<!-- fourth comment -->
<div><div><div><div><div><div><span><div id="node4"><span><span><b><em>
<i><strong><pre></pre></strong></i><div><div id="node5"><div></div></div></div></em>
</b></span><span><span id="node6"></span></span></span></div></span></div></div></div></div></div></div>
<div>
<div>
<div id="node7">
<div>
<div>
<div id="node8">
<span>
<!-- fifth comment -->
<div>
<span>
<span>
<b>
<em id="node9">
<i>
<strong>
<pre>
</pre>
</strong>
</i>
<div>
<div>
<div>
</div>
</div>
</div>
</em>
</b>
</span>
<span>
<span id="node10">
</span>
</span>
</span>
</div>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Something like this?
var wholeDocument = document.getElementsByTagName('html')[0]
var findNode = document.getElementById('whatever')
var documentUpToFindNode = wholeDocument.substr(0, wholeDocument.indexOf(findNode.outerHTML))
var nlsUpToFindNode = documentUpToFindNode.match(/\n/g).length
This can be done. Start by getting the highest node in the document like this:
var htmlNode = document.getElementsByTagName('html')[0];
var node = htmlNode;
while (node.previousSibling !== null) {
node = node.previousSibling;
}
var firstNode = node;
(this code was tested and retrieved both the doctype node as well as comments above the html node)
Then you loop through all nodes (both siblings and children). In IE, you'll only see the elements and comments (not text nodes), so it'll be best to use FF or chrome or something (you said it wouldn't have to be cross browser).
When you get to each text node, parse it to look for carriage returns.
You could try: -
- start at the 'whatever' node,
- traverse to each previous node back to the doc begining while concatenating the html of each node,
- then count the new lines in your collected HTML.
Post the code once you nut it out coz thats a good question :)

Categories