get textNode of a elementNode of a web page via javascript - javascript

In a web page,i want to get every visible text in a textnode.I don't want to put all the result into one array.I mean, when i meet a visible text, i will do something else.
How could i achieve it?

I guess you want something like this:
<script type="text/javascript">
function textnodes(){
function iterate(node){
var nodes=node.childNodes
var len=nodes.length
for(var a=0;a<len;a++){
if(nodes[a].nodeType==3){
if(!nodes[a].nodeValue.match(/^[\s]*$/)){
alert(nodes[a].nodeValue) //Insert your code here.
}
}
else{
if(nodes[a].nodeName.toLowerCase()!="script"){
iterate(nodes[a])
}
}
}
}
iterate(document.body)
}
textnodes()
</script>
The script as it is might be a bit overzealous, you get along a lot of invisible text nodes, you can sort those out if you don't need them.
Edit: Modified to sort out invisible nodes since you specifically requested only visible nodes.

Related

Javascript Help on Dropdown filter

I was able to find a solution on Stackoverflow that display HTML "li" elements based on a filter (see attachement). Essentially based on css class'es defined in HTML elements, it populates the drop down list that you can select from.
I would like to be modify javascript below so that when you navigate to one of the "li" elements pages (as seen here: https://jsfiddle.net/quwfmepL/2/ e.g. Note: Chose one Test1 element and it goes to the page1.html page) ..but when you hit the back button on the page1.html to page where filter resides, it doesn't remember last filter choice. As it does now, you are required to filter same choice again. I think what I need to do is look at the browser history, but not sure if there is an easier option. I was hoping it could be in the format of query string or like.
<script type="text/JavaScript">
$(document).ready(function() {
var $tagList = $('#tag-list'),
optionArr = [];
$("#demo-list li a").each(function(index, item) {
$.each($(this).attr('class').split(' '), function(i, option){
if ($.inArray(option, optionArr) == -1) {
$tagList.append('<option value="'+option+'">'+option.replace('-', ' ').replace('_', ' ')+'</option>');
optionArr.push(option);
}
});
});
// Look at the URL for filter and modify here #
$tagList.on('change', function() {
var selection = $tagList.val();
if (selection == "all") {
$('#demo-list li a').show();
} else {
$('#demo-list li a').hide();
$('#demo-list li a.'+selection).show();
}
});
});
</script>
Any suggestions or hints? Any help is appreciated.
Fiddle is acting a bit strangely (not working) for me.
You may want to just set a cookie inside of the .change function, that'd probably be the easiest way to do it. When the filter page loads, check to see if the cookie is set, and if it is, run the filter based on the stored cookie value.
Try out: https://github.com/js-cookie/js-cookie
Alternatively, and probably even better, you can use webstorage (localstorage) to accomplish the same thing.
http://www.w3schools.com/html/html5_webstorage.asp

Deleting and inserting Code in a DIV via jQuery

I know this has been adressed before, but I can't seem to get it working for me.
I am trying to create a football pitch with editable players via HTML/JavaScript/jQuery.
I can produce the field the first time when loading the page without any problems. The code looks like this:
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2);
</script></div>
appBuilder() looks like this:
var appBuilder = function (team1, team2) {
team1.Display();
team2.Display(); }
It simply creates the players on the pitch for both teams. As it does. I now want to push an input-button to call a function appUpdate(), which deletes the content of #pitch and puts the appBuilder()-part in again as to renew it (if I changed or added players):
var appUpdate = function () {
var newContent = "<script type='text/javascript'>appBuilder(team1, team2);</script>";
var updateItem = $('#pitch');
updateItem.empty();
updateItem.append(newContent);}
Here is what drives me nuts: It seems to work just fine up to and including the empty()-function. So the code has to be fine.
But when I try to append newContent to the #pitch-DIV, the programm seems to completely delete everything inside <head> and <body> it recreates a clean html-file (with empty html-, head-, body-tags) and inserts my players inside <body>.
Any ideas as to why it is doing that?
Thanks in advance!
UPADTE: The solution was a rookie mistake (which is fitting, since I'm a rookie). The Team.Display()-method was trying to do a document.write() call. As I learned: If you call document.write once the document is fully loaded, it will delete your site. Thanks to jfriend for the solution! :)
If you call document.write() AFTER the document has finished loading, then it will clear the current document and create a new empty one.
What you need to do is use DOM insertion operations rather than document.write() to add/change content in the DOM once the document has already loaded.
My guess is that the .Display() method is using document.write() and you need to change the way it works to insert content into a parent node rather than write it into the current position.
Some ways to insert content:
var newNode = document.createElement("div");
node.appendChild(newNode);
node.innerHTML = "<div>My Content</div>";
Or, if you're using jQuery, you can use it's wrappers for this:
obj.append("<div>My Content</div>");
obj.html("<div>My Content</div>");
.html() would empty and fill the div at once. Have you tried that ?
updateItem.html(newContent);
I proposed a JQuery replacement for your code that does what you want, ion the style of your own typing.
Note that I kept the .html() call to mimic your "empty()" function, but it is not necessary. Simply put he code in the append, straight into the html() et get rid of the extra unnecessary remaing bit of code.
My code replacement, as a 100% functioning .html file. Hope it helps, cheers.
<html>
<header>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var appBuilder = function (team1, team2) {
//team1.Display();
//team2.Display();
}
var team1, team2;
</script>
</header>
<body>
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2); // Original code to be updated
</script>
</div>
<script>
var appUpdate = function () {
$("#pitch").html("<!-- Old javscript code has been flushed -->").append($("<script />", {
html: "appBuilder(team1, team2); // brand new, replaced code"
}));
}
appUpdate();
</script>
</body>
</html>

Javascript Validation of dynamic textarea

Hi I'm using a CMS which dynamically creates textareas on product pages of an ecommerce site. The text area has a different ID on each different product page. I am in need of some javascript that will check if all textareas on a page are empty and if so display a warning message. I cant assign an id to the text areas so cant use this script I normally use. Any help is much appreciated!
function validate() {
var val = document.getElementById('textarea').value;
if (/^\s*$/g.test(val)) {
alert('Wrong content!');
}
}
Hey Benjamin thanks for your reply, I couldn't get the code working in comments, thinking I'm having a bad day. So as i was trying to say I'm not the greatest at Javascript (but eager to learn!) I've added this to my page but it doesn't appear to work:
<script>
var areas = document.getElementsByTagName("textarea");
// now iterate them for
(var i=0;i<areas.length;i++){
var val = areas[i].value;
if (/^\s*$/g.test(val)) {
// whatever
}
} </script>
With this as in the body
<div class="description">Further Details <br>
<textarea id="catProdInstructions_6486638" class="productTextarea"></textarea>
</div>
Thanks for your time on this :)
You can use getElementsByTagName to fetch all <textarea>s.
It returns a NodeList of all the text areas currently in the page which you can iterate.
var areas = document.getElementsByTagName("textarea");
// now iterate them
for(var i=0;i<areas.length;i++){
var val = areas[i].value;
if (/^\s*$/g.test(val)) {
// whatever
}
}
The NodeList returned is live , this means that it'll update itself automatically as new textarea elements are added dynamically even if you fetch them with ajax or create them with code.

not able to append html using jQuery (JavaScript)

In this jquery plugin:
http://www.stahs.org.uk/jquery.infinitecarousel.bak
There's this line:
$(obj).append('<div id="textholder'+randID+'" class="textholder" style="position:absolute;bottom:0px;margin-bottom:'+-imgHeight*o.textholderHeight+'px;left:'+$(obj).css('paddingLeft')+'"></div>');
Problem is when it dumps the text node in this div, it aligns to the top of the div. I want text to align to bottom of div. So I decided to create another div within this div:
$(obj).append('<div id="textholder'+randID+'" class="textholder" style="position:absolute;bottom:0px;margin-bottom:'+-imgHeight*o.textholderHeight+'px;left:'+$(obj).css('paddingLeft')+'"></div>');
console.log($('#textholder'+randID));
$('#textholder'+randID).append('<div style="display:table-cell; height: 94.25px; width: 1000px; vertical-align:bottom;"></div>');
The console outputs this:
[div#textholder35196647.textholder]
[div#textholder62315889.textholder]
[div#textholder95654959.textholder]
However, my above append is not working. The nested div never shows up, so when I later do this:
if(t != null)
{
$('#textholder'+randID+' div').html(t).animate({marginBottom:'0px'},500); // Raise textholder
showminmax();
}
No text becomes visible because the nested div never gets created.
So I am extremely confused. If you look at original plugin, this line works:
$('#textholder'+randID+' div').html(t)
How is it able to target the right div here yet when I append to it right after it's created, it doesn't exist, as you guys suggest?
This doesn't work either:
var $texthold = jQuery('<div id="textholder'+randID+'" class="textholder" style="position:absolute;bottom:0px;margin-bottom:'+-imgHeight*o.textholderHeight+'px;left:'+$(obj).css('paddingLeft')+'"></div>');
$(obj).append($texthold);
$texthold.append('<div></div>')
Thanks for response.
It sounds as though perhaps randID has been modified between the $(obj).append... line and your added $('#textholder'+randID)... line. Are you quite sure the value of randID is the same on the two lines?
Are you sure that $(obj) really refers to the element you want to append to? Just in case, you might want to try it the other way round:
$('<div id="textholder'+randID+'" class="textholder" style="position:absolute;'
+'bottom:0px;margin-bottom:'+(-imgHeight*o.textholderHeight)
+'px;left:'+$(obj).css('paddingLeft')+'"></div>'
).appendTo(obj);
It appears this worked:
function showtext(t)
{
if(t != null)
{
if(typeof $('#textholder'+randID).find('div')[0] == 'undefined'){
$('#textholder'+randID).append('<div style="display:table-cell; height: 94.25px; vertical-align:bottom;"></div>');
}
$('#textholder'+randID+' div').html(t);
$('#textholder'+randID).animate({marginBottom:'0px'},500); // Raise textholder
showminmax();
}
}
It's just kind of crazy I had to resort to using typeof to check whether div is declared or not. Why the author of the plugin decided to randomly assign integers as ids of divs is beyond me. By doing that, it appears javascript has difficulty retaining the randomly created id. That's my only explanation for the unusual behavior I could come up with.
Try:
$(obj).after('html');
Documentation is here.

How do I auto-scroll to a specific table row?

I have an html page with a header, a table containing 100 items and a footer.
When there is a search, I highlight the row containing the data.
However, if the highlighted row is row 75, the user has to scroll down to find it.
How can I automatically scroll to that row?
I did see scrollTo() but see it only takes axis points.
Any suggestions?
Thanks.
(Using cgi in C, html, css and javascript/jquery)
You should be able to use scrollIntoView(). (It's on the DOM elements directly.)
Be aware that there are some layout situations where scrolling something on the page can cause IE6 and 7 to decide that random other stuff needs to be scrolled too.
try this:
<script>
function ScrollToElement(theElement){
var selectedPosX = 0;
var selectedPosY = 0;
while(theElement != null){
selectedPosX += theElement.offsetLeft;
selectedPosY += theElement.offsetTop;
theElement = theElement.offsetParent;
}
window.scrollTo(selectedPosX,selectedPosY);
}
</script>
<body onload="ScrollToElement(document.formName.elementName)">
I think you can do something like this:
Use this line where ever you like,
<a id="bookmark"></a>
and when you start your page, call it like this:
http://mypage.com/setting.php#bookmark
That worked for me without showing the anchor.
Check again for using bookmark in html
EDITED:
Check: JavaScript - Jump to anchor

Categories

Resources