JavaScript - Giving A Child Element A Link
I was wondering if there was any way I can give a child element, preferably the first one, a link through a parent element with an ID.
An example: Code: <div id="parent"> <a href="/">Name</a> <-! start message -> <b>child element text</b> <-! end message -> </div> I want the bold tag to have the link, basically. But through javascript. Similar TutorialsThe bit of code in bold in the code below is giving me this error in IE: Error: Code: Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; Tablet PC 2.0; InfoPath.2; OfficeLiveConnector.1.4; .NET CLR 3.0.30729; OfficeLivePatch.1.3; MSN OptimizedIE8;ENGB) Timestamp: Tue, 16 Mar 2010 15:07:11 UTC Message: HTML Parsing Error: Unable to modify the parent container element before the child element is closed (KB927917) Line: 0 Char: 0 Code: 0 URI: http://www.mateinastate.co.uk/users/mateinastate Code: Code: if(document.getElementById('msn1').innerHTML=="") { document.getElementById('msn1').style.display='none'; } if(document.getElementById('yahoo1').innerHTML=="") { document.getElementById('yahoo1').style.display='none'; } if(document.getElementById('skype1').innerHTML=="") { document.getElementById('skype1').style.display='none'; } if(document.getElementById('facebook1').innerHTML.toLowerCase().substr(0,18)=='<a href="http://">') { document.getElementById('facebook1').style.display='none'; } else if(document.getElementById('facebook1').innerHTML.toLowerCase().substr(0,11)=='<a href="">') { document.getElementById('facebook1').style.display='none'; } else { document.getElementById('fbook-add').innerHTML='Facebook Profile'; } What it's saying isn't actually true (I don't think)... this is how the section is laid out: Code: <div id="submenu1" class="anylinkcss"> <ul> <li class="contact-pm"><a href="/index.php?do=pm&act=new&to=$RateViewProfileUserName$&returnurl=$ReturnURL$">PM me</a></li> <li class="contact-email"><a href="/index.php?do=email&id=$RateViewProfileUserId$">E-mail me</a></li> <li class="contact-msn" id="msn1">$RateViewProfileUser-profile_msn$</li> <li class="contact-yahoo" id="yahoo1">$RateViewProfileUser-profile_yahoo$</li> <li class="contact-skype" id="skype1">$RateViewProfileUser-profile_skype$</li> <li class="contact-facebook" id="facebook1"><a href="$RateViewProfileUser-profile_facebook$"><span id="fbook-add"></span></a></li> </ul> </div> <script type="text/javascript" src="/html_1/js/contact-information.js"></script> Does anyone know why this might error in just IE? Hi Experts, i have 2 JS array and i need to have dependency between them knowing that 1st Array has parent element of the 2nd one. i.e ARRAY1 ID VAL ID2 2 Dep1 10 3 Dep2 20 4 Dep3 30 ARRAY2 ID VAL ID2 PARENT 20 team1 11 10 21 team2 12 10 22 team3 13 20 23 team4 14 30 i need to have two different DDL's where when i choose VAL = Dep1 on ARRAY1 , i should see on the 2nd DDL only elements with parent corrsponding to Dep1 ( PARENT =10). how this can be possible thanks Hi, I have a small problem with a page I'm working on. I have an anchor tag inside a table that has a mouseover event that updates a contextual help box. I need to add a similar mouseover event to the anchor tag that does the same thing, but updates the help box with different text. The problem I have is that when the mouse is over the table, no matter if I move the mouse over the anchor, the help text only displays the message that is passed from the table's mouseover function call. I think the solution *may* be something to do with event bubbling, but I'm not exactly sure how to implement it. The code I'm dealing with is below: The code below is PHP. The table mouseover (for reference): Code: echo "<table class='cleanTable' width='100%' style='margin-top: 5px'"; echo " onMouseOver=\"updateHelpText('Message 1.');\" onMouseOut='clearHelpText();'>"; echo "<tr><th> </th><th> </th><th>First Name</th><th>Surname</th><th>Last Login</th></tr>"; The anchor mouseover: Code: echo "<tr class='cleanrow'><td><a href='newMember.php'><img border='0' src='images/icon_add.gif'></a></td><td></td>"; echo "<td colspan='3'><a class='workbenchLink' href='newMember.php' onMouseOver=\"updateHelpText('Message 2');\" onMouseOut='clearHelpText();'>Invite a new colleague...</a></td></tr>"; echo "</table>"; The function (javascript): Code: function updateHelpText(newText) { document.getElementById("helpBox").innerHTML = "<h4> " + newText + "</h4>"; } Any help with this would be great, thanks. Hi, I'm relativly new to JS and brand new to the forum so you might need to dumb down your replys for my slightly lacking knowledge. That being said I do have a very solid grasp of html, css and am getting there with JS and its various frameworks. I'm integrating wordpress into an existing site for a friend and currently have the main blog page appear in a DIV. This is the best way to integrate in this case due to many reasons mostly of way the site is constructed. Code: <div class="scroll-pane" id="scrollbox"> WORDPRESS BLOG </div> My issue is that links within that DIV, in the blog, when clicked redirect the page. The simple answer to this would be to have them just open in a new page, which I can easily do with the below code. Code: function Init() { // Grab the appropriate div theDiv = document.getElementById('scrollbox'); // Grab all of the links inside the div links = theDiv.getElementsByTagName('a'); // Loop through those links and attach the target attribute for (var i=0, len=links.length; i < len; i++) { // the _blank will make the link open in new window links[i].setAttribute('target', '_blank'); } } window.onload = Init; But what I'd rather it do is have any link clicked inside the DIV to reload in that same DIV, similar to an iframe, but obviously without using an iframe, due to it's compatibility issues. Is this possible by editing the above code? If not what do I need? Thanks in advance for any help! I've been handed an html document that contains a centered, scrollable <iframe> element with a static height and width. This iframe element displays a simple html document that houses the 'terms of service' text. Their goal is to have it to where the <a href> link at the bottom that is shown to the user as 'next' is disabled until the user scrolls to the bottom of the terms of agreement box. The clickable link could be a button, image or text (no preference). They have to have it this way for legal reasons and radio buttons or checkboxes will not suffice unfortunately. Question: What is the best way to go about doing this that seems to be cross-browser friendly (especially IE7). I offer $10 via paypal for well commented method/script. Hi, I'm kinda hoping this is possible but haven't found any reference to it... I have a parent page that opens a popup on click that launches a sidebar navigation on the right of the screen and resizes the parent page. What I am wanting to do is create a second popup (approx 250px high) that opens below the navigation (which is only around 600px high) but I have noticed that even when you have no status bar in the popup windows, they can still end up overlapping because of additional tools or plugins that the viewer has in their browser. Is there any way to get the popups to butt up against each other instead of overlapping? More like a relative popup? Any assistance would be appreciated. :-) Hi all. I'm developing After Effects scripts using their Extendscript language - essentially just Javascript with various extensions. I've defined a class, called ScriptSetting, which handles reading and writing of user settings to a prefs file. For example I create a ScriptSetting variable as follows: Code: var mySetting = new ScriptSetting("myScript", "thisSettingKey", 200); This calls the ScriptSetting constructor function: Code: function ScriptSetting(sectionName, keyName, defaultValue) { this.sectionName = sectionName; // Store the type of this setting for conversion later this.defaultType = defaultValue.constructor; // Convert any type to a string value for storing defaultValue = defaultValue.toString(); this.keyName = keyName; if(!app.settings.haveSetting(this.sectionName, this.keyName)) { this.value = defaultValue; this.saveSetting(); } else this.value = this.getSetting(); } This calls some of Extendscript's built-in functions, like app.settings.haveSetting() This all works fine - I can then later access mySetting's value with, for example alert(mySetting.value) since I've defined value as part of the class constructor function. However what I'd ideally like to do, if at all possible is to lose the .value part and just be able to access the setting value directly from the setting variable, so in this case alert(mySetting). At the moment, this will just return object Object. Naturally this is because mySetting is an instance of the ScriptSetting object. But I wondered if you can spoof this with a different type (i.e. Array or Number) when accessing it as part of a statement e.g. if(mySetting == 200) { // do something } but still retain all its prototyped methods, e.g. Code: mySetting = 300; mySetting.saveSetting(); Is this possible in Javascript? It's not a deal-breaker - I just want to make my code a bit more readable. Many thanks in advance, Christian Hi I'm using an image hover script so when you mouseover a thumbnail it displays a larger version of the image in a javascript/jquery nice image popup (not a popup window but like a floating image). It comes from the script here http://cssglobe.com/lab/tooltip/02/ The trouble is, I need the large image to display above and to the left of the thumbnail - not to the right and below. Looking in the js file I see these values: Code: this.imagePreview = function(){ /* CONFIG */ xOffset = 10; yOffset = 30; // these 2 variable determine popup's distance from the cursor // you might want to adjust to get the right result I've tried making these -500 and -500 but it just makes them like the negative value was not added (the large image goes down 500px). So as I don't understand javascript code I'm thinking that is not the way to give a negative number? Would appreciate any help please When i did a view source , checkbox names are displayed as MedicalAction_listOfTransfers_[0]__rowSelected' so each checkbox has different name and id as well all i am trying to do here is to put a checkall/uncheckall option , also in the jsp page we have a pagination so is that something that cause the checkbox value as null ? function MoveAll(){ var lengthofRecords = document.getElementById('resultsSize').value; for (i = 0; i < lengthofRecords; i++){ var name = 'MedicalAction_listOfTransfers_'+i+'__rowSelected'; var checkBox = document.getElementById(name); alert("check box B4: " + checkBox); - // I AM GETTING NULL VALUE HERE checkBox.checked=checkBox.checked == false ? true:false; alert("check box A4: " + checkBox.checked); //checkBox.checked = checkBox.checked? true:false; } } Please help i am newbie How do I store how many Windows my house has as a variable as this script I made isn't working. Quote: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/javascript"> var test function show_prompt(a_bac) { prompt(a_bac) } function show_alert(a_baf) { alert(a_baf) } </script> <body> <!-- How do I store how many Windows my house has as a variable? --> <input type="button" value="click" onclick="var theanswer = prompt('How many windows does your house have?')" /> <input type="button" value="answer" onclick="alert(theanswer)" /> </body> </html> In the routine below I'm trying to make sure a date isn't > today. It WORKS FINE in Firefox but I get a NaN in MSN. WHY? And how do I fix it? Thanks Note: ( 2010 2 1 is in testfield and 2010 4 20 is in todayfield) var todayfield = tdyear+" "+tdmonth+" "+tdday; alert ("today=" + todayfield); alert (Date.parse(testfield)); alert (Date.parse(todayfield)); if (Date.parse(testfield) <= Date.parse(todayfield)) Does anyone know how to make these things work? I have to make this hanjie puzzle and I have at least gotten the black squares to display. I have worked through all the directions three times and run it through the Firebug. I don't understand what it is asking for and don't know how to change the code to make this work, someone please help me! Code: window.onload = setPuzzle; var allCells = new Array(); function setPuzzle() { var puzzleTable = document.getElementById("puzzleCells"); allCells = document.getElementsByTagName("td"); for (var i =0; i < allCells.length; i++) { allCells[i].style.backgroundColor = "white"; allCells[i].onclick = changeColor; } document.getElementById("solution").onclick = showSolution; document.getElementById("hide").onclick = hideSolution; document.getElementById("solution").onclick = showSolution; document.getElementById("check").onclick = checkSolution; document.getElementById("uncheck").onclick = uncheckSolution; } function changeColor(){ this.style.backgroundColor = (this.style.backgroundColor == "black") ? "white" : "black"; } function showSolution(){ for(var i=0;i<allCells.length; i++) { if(allCells.className == "dark"){ allCells[i].style.backgroundColor = "black"; } else { allCells[i].style.backgroundColor = "white"; } } checkCount = 0; } function hideSolution() { for(var i=0;i<allCells.length; i++) { allCells[i].style.backgroundColor = "white"; } checkCount = " "; } function checkSolution() { var checkCount = 0; for (var i = 0; i< allCells.length; i++) { if (allCells[i].style.backgroundColor == "black" && allCells[i].className != "dark") { allCells[i].style.backgroundColor = "red"; } else if (allCells[i].className == "dark" && allCells[i].style.backgroundColor == "white"){ checkCount++; } return checkCount.value; } } function uncheckSolution() { for (var i = 0; i< allCells.length; i++) { if (allCells[i].style.backgroundColor == "red") { allCells[i].style.backgroundColor = "black"; } checkCount = " "; } } Dreamweaver is giving me a syntax error, but i dont understand what is wrong. i copied the line from the source code of the demo file included in the download and it it still telling me there is a syntax error. obviously something is wrong bc my slider isnt auto-sliding. so then i tried copying and pasting from the source code of the web page i got the slider from (http://www.ndoherty.biz/demos/coda-slider/2.0/) Dreamweaver then moved the syntax error warning to the line that only contains my closing script tag what am i doing wrong? why am i getting syntax errors? how can i make this thing autoslide? full code available at: http://mydomainsample.com/fire_rebuild All, I have the following code: console.log("My num is: " + num); console.log("My lat is: " + lat); console.log("My lat length is: " + lat.length); console.log("My long is: " + long); When I get the output, I get the following: My num is: {"1":1,"2":2} My lat is: {"1":"40.59479899","2":"41.4599860"} My lat length is: 36 My long is: {"1":"-75.5549650","2":"-87.596430"} I'm confused on why the length is saying 36 when it's obviously two and the other output shows that??? i'm working with a javascript on a drupal website, but the saving function seems to work only as soon as i click 2 times on the "save" button. the code that fires the function is: Code: var param ="&usuario="+usuario+"&nivel="+nivel+gano+porc_gano+gasto+porc_gasto+tengo+porc_tengo+debo+ porc_debo+plazo_debo; var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; s.src = server_direction +"setMisDatos?callback=respuestaGuardarMisDatos¶m="+encodeURIComponent(param); var h = document.getElementsByTagName("script")[0]; h.parentNode.insertBefore(s, h); //or h.appendChild(s); the chrome console tells me the error is in the last line i copied, but i don't undertand what kind of error it is. using chrome console (specifically the "network" one), i see that it's written in red, status/text "failed", type "undefined" size/content "13 B / 0 B"; when it works it's: status/text "200/OK", type "text/json", size/content "256 B/ 38B". i'm not an expert with this, is there some more information that could be useful? the code fires a netbeans function, that stores data to a postgresql database, so i have like 100 variables that has to be stored when i click on the "save button". Actually before i put parentNode.insertBefore, there used to be appendChild(s), but then i found out this algorithm from google analytics, which seems to be working better than the previous one. Having said that, i can tell you that the GET works after the first time i click perfectly, with some weird things happening, like if i browse another tab for a while, then go back to the page, and click on save, it won't work again (same error). The variables are written like this: Code: var plazo_debo_casa1 = (getValor("plazo_debo_casa1")); var plazo_debo_casa2 = (getValor("plazo_debo_casa2")); var plazo_debo_casa3 = (getValor("plazo_debo_casa3")); var plazo_debo_prestamo1 = (getValor("plazo_debo_prestamo1")); var plazo_debo_prestamo2 = (getValor("plazo_debo_prestamo2")); var plazo_debo_prestamo3 = (getValor("plazo_debo_prestamo3")); var plazo_debo ="&plazo_debo_casa1="+plazo_debo_casa1+"&plazo_debo_casa2="+plazo_debo_casa2+"&plazo_debo_casa3="+plazo_debo_casa3+"&plazo_debo_prestamo1="+plazo_debo_prestamo1+"&plazo_debo_prestamo2="+plazo_debo_prestamo2+"&plazo_debo_prestamo3="+plazo_debo_prestamo3; and then together in the "param" variable. Is it clearer now? i tried to copy document.head.appendChild(s); instead of parentNode.insertBefore(s,h), but it still behaves the same way. Still not any suggestions? This is part of the javascript file loading on my page, and since the function setMisDatos is in netbeans and it works correctly as soon as it's fired (at least, that's what i notice after the first click), i don't think it's worth copying part of it here, right? are there maybe too many variables for the GET method? is there a way to check GET errors? i'm sorry for not being an expert but i would really like some help here. Let's say I set up a table with <table name=tile1 id=justChecking border=1> When I want to do something with it or get its position, using document.tile1, I get nothing but undefined. But id and getElements work fine: the line alert(document.getElementById('justChecking')); returns [object], and the lines Code: var handle = document.getElementsByTagName("table")[0]; alert("Or, it's seen as " +handle+ " called " +handle.name); return Or, it's seen as [object] called tile1. So this means that accessing a table via a name isn't doable? How is it that this is a shortcoming that seems to be the nature of IE, and yet not mentioned or searchable? Or maybe I'm doing something moronic. -------------------------------------------------- The code here isn't showing anything new ... merely saving a round of posts in case someone wants the whole thing or wants to copy/paste it. Code: <HTML><BODY> <TABLE name=tile1 id=justChecking border=1><tbody><tr><td>Very odd,<td>I say.</table> <br> <script type="text/javascript"> alert("Seeking tile1 as " +document.tile1); alert("Maybe detectable as " +document.getElementById('justChecking')); var handle = document.getElementsByTagName("table")[0]; alert("Or, it's seen as " +handle+ " called " +handle.name); </script> </body></html> I think the `getJSON` should be taking the JSON URL and returning it as a response - The data file has `Author x3 Body x3 and Title x3`. Once it has this it should map it into the `nodes` and give me three nodes for each section of data. However currently its giving me the `console.log` output that I have below and nothing in my `nodes var` **Console Log:** Code: script.js:7 [Object, Object, Object]0: Object1: Object2: Objectlength: 3__proto__: Array[0] **Code:** Code: $(document).ready(function(){ var url = "assets/js/data.json"; $.getJSON(url).done(function(response) { var nodes = response.map(function(i) { return $('<div>').append( $('<div>', {class: 'title'}).text(i.title), $('<div>', {class: 'author'}).text(i.author), $('<div>', {class: 'body'}).text(i.body) ); console.log(response); }); }); });//Ready function closed Reply With Quote 01-08-2015, 10:56 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts The data file has `Author x3 Body x3 and Title x3`. Literally??? That is, it has something like Code: { Author: "Adam", Author: "Bob", Author: "Carol", Body: "Somethhing...", Body: "something else ...", Body: "more stuff...", Title: "Book one", Title: "Book two", Title: "Book three" } ??? I'm sure that's not what you meant, but what *DID* you mean? Why not simply copy/paste the contents of "data.json" to here? I have a CSS file associated with this that sets the width at "200px." However, I am getting a 40px wide dropdown. Can anybody catch an error in here? Using console.log, I found that el, as soon as it is defined, is = div.dropdown. As soon as .width comes into the picture, it returns as six consecutive 101px and a ton of 40px after that... and continues returning those values till the end. I appreciate any input!! Code: var Dropdown = function(el) { this.el = el; this.handle = el.find("div.dropdown-text"); this.options = el.find("div.dropdown-options"); this.optionsWrap = this.options.parent(); this.action = el.attr("action"); this.type = el.attr("type"); this.target = el.attr("target"); this.Init(); } Dropdown.prototype.Init = function() { var self = this; var extraPadding = 40; this.isShown = false; console.log(this); this.width = this.options.outerWidth() + extraPadding; this.height = this.options.outerHeight(); if (this.height > 300) { this.height = 300; this.options .height(300) .width(this.width + 12) .addClass("scroll-pane") .jScrollPane({ showArrows: true, scrollbarWidth: 9 }) this.width += 12; } else { this.options.width(this.options.width() + extraPadding); } var newWidth = (this.width < 220) ? this.width : 220; this.el.width(newWidth); this._AddShadow(); this.optionsWrap.css({ display: "none", visibility: "visible", width: this.width + 5, height: this.height + 5 }); this._SetEvents(); }; Dropdown.prototype.Toggle = function(force) { if (this.isShown && !force) { this.optionsWrap.hide(); this.isShown = false; } else if (!this.isShown && false !== force){ this.optionsWrap.show(); this.isShown = true; } } Dropdown.prototype._AddShadow = function() { var shadowWidth = 5, layer; for (var i = 0; i < shadowWidth; i++) { layer = $('<div class="shadow_layer"> </div>'); layer.css({ opacity: 0.055 * (i + 1), top: (shadowWidth - i), left: (shadowWidth - i), height: this.height, width: this.width }); this.optionsWrap.prepend(layer); } } Dropdown.prototype._SetEvents = function() { var self = this; this.el.bind('click', function(e) { var current = $(e.target); var type = current.attr("type"); if (current.hasClass('dropdown-text') || current.hasClass('dropdown-arrow')) { if (!self.isShown) { page.HideAllDropdowns(); } self.Toggle(); return false; } if (current.hasClass('dropdown-opt')) { switch (type) { case 'auto': case 'basic': var html = current.html(); self.handle.html(html); self.options.find('a.dropdown-opt').each(function() { $(this).removeClass('selected'); }); if ('auto' == type) { page.common.Update({ url: current.attr('path'), params: current.attr('params'), target: self.target, parent: true, method: "POST", handler: { handler: function(results) { var action = this.attr("action"); if (action) { page.events.Fire(action, this, results) }; }, context: current } }); } current.addClass('selected'); self.Toggle(); return false; case 'multi': current.toggleClass('selected'); break; case 'function': var html = current.html(); self.handle.html(html); current.Fire(); self.Toggle(false); break } } return false; }); } i had one window with few controls and two buttons, one button click i am opening another small window by using window.open, in this window i had one close button. on click of close button what i want is i want to click the second button which exists in the parent window, and i want to close the chield window. for that i am coding window.opener.document.getElementById('pbGo').click(); self.close(); but i am getting error, in the second button i put alert message for testing purpose. where i am doing wrong i dont know. Any help please. thanks Ok, so the nth-child format is .class:nth-child(n){} Does anyone know of a way to dynamically set n? What I am trying to do is highlight the nth child element, but I need to be able to alter n based on the state. |