Find an anchor in a Div with javascript - javascript

In javascript I have a reference to a div. In that div is an anchor element with a name='foundItem'
How do I get a reference to the anchor with the name foundItem which is in the Div I have the reference of?
There are 'many' foundItem anchors in other divs on the page. I need 'this' DIVs one.

// assuming you're not using jquery or mootools
// assume div is mydiv
var lst = mydiv.getElementsByTagName('a');
var myanchor;
for(var i=0; i<lst.length; ++i) {
if(lst[i].name && lst[i].name == 'foundItem') {
myanchor = lst[i];
break;
}
}
// the mootools method
var myanchor = $(mydiv).getElement('a[name=foundItem]');

You can use the getElementsByTagName method to get the anchor elements in the div, then look for the one with the correct name attribute:
var found = null;
var e = divReference.getElementsByTagName('A');
for (var i=0; i < e.length; i++) {
if (e[i].name && e[i].name == 'foundItem') {
found = e[i];
break;
}
}
If found is not null, you got the element.
If you happen to use the jQuery library, you can let it do the searching:
var found = null;
var e = $(divReference).find('a[name=foundItem]');
if (e.length == 1) found = e.get(0);

Use a JavaScript library like jQuery and save yourself time.
var theAnchor = $('#divId a[name=foundItem]');

Using jquery, it's dead easy:
<script type="text/javascript">
$(function(){
var item = $("#yourDivId a[name=foundItem]")
)};
</script>
Update:
As per the comments, if you have control over what to id/name/class your anchor tag/s, it would be best to apply a class to them:
<div id="firstDiv">
test
</div>
<div id="secondDiv">
test another one
</div>
<!-- and so forth -->
<script type="text/javascript">
$(function(){
var item = $("#firstDiv a.foundItem");
alert(item.html()); // Will result in "test"
var item2 = $("#secondDiv a.foundItem");
alert(item2.html()); // Will show "test another one"
)};
</script>
If you're doing anything with javascript, jQuery saves you tons of time and is worth investing the effort to learn well. Start with http://api.jquery.com/browser/ to get an intro to what's possible.

Not sure if this helps, but wanted a function to handle the load of a page dynamically and scroll to the anchor of choice.
function scrollToAnchor(anchor_val) {
alert("" + anchor_val);
var page = document.getElementById('tables');
var found = null;
var cnt = 0;
var e = document.getElementsByTagName('a');
for (var i = 0; i < e.length; i++) {
if (e[i].name && e[i].name == anchor_val) {
found = e[i];
break;
}
cnt++;
}
if (found) {
var nPos = found.offsetTop;
alert("" + nPos);
page.scrollBy(0, nPos);
} else {
alert('Failed with call of scrollToAnchor()' + cnt);
}
}

Related

multiple onclick functions not possible?

I'm new to javascript (and I'm not allowed to use jQuery in class) and I'm struggling with onclick functions.
I want two separate sentences to turn green and the other one pink when I click on it so I gave both of them a different id.
for(var i = 0; i < content.length; i++){
var contentText = content[i];
var opening = document.createElement("p");
opening.id = "opening";
if(content[i].id ==="opening"){
opening.innerText = contentText.text;
}
textContainer1.append(opening);
document.getElementById("opening").onclick = function opening(){
document.getElementById("opening").style.color = 'green';
}
This is the first onclick function and it works like it should! But when I add the other sentence underneath:
for(var j = 0; j < content.length; j++){
var contentText2 = content[j];
var second = document.createElement("p");
second.className = "chapter-1";
second.id = "second";
if (content[j].id ==="second"){
second.innerText = contentText2.text;
}
textContainer2.append(second);
}
document.getElementById("second").onclick = function second(){
document.getElementById("second").style.color = 'pink';
}
The second one doesn't work anymore. I really can't figure out how to solve this and I need several ones in the same file. Can someone please help?
EDIT
I found out that it only works for the first thing in the json list, and not for the second, or third, etc. So I think I need a for loop to search within the elements, but I'm not sure how to do that in this case...
New answer
I think you've missed a } in the first bit of code.
for(var i = 0; i < content.length; i++){
var contentText = content[i];
var opening = document.createElement("p");
opening.id = "opening";
if(content[i].id ==="opening"){
opening.innerText = contentText.text;
}
textContainer1.append(opening);
}
document.getElementById("opening").onclick = function opening(){
document.getElementById("opening").style.color = 'green';
}
Old answer with probably better code
I may be misunderstanding you, but if you want your sentences to go green/pink when clicking on them, you just need the second function in each of your examples.
<p id="opening" onclick="opening();">opening</p>
<p id="second" onclick="second();">second</p>
<script>
var opening = function() {
document.getElementById("opening").style.color = "green";
}
var second = function() {
document.getElementById("second").style.color = "pink";
}
</script>
This makes opening go green when one clicks it and second go pink when one clicks it.
Alternatively, if you want to assign it without adding onclick in HTML:
document.getElementById("opening").onclick = function() {
document.getElementById("opening").style.color = "green";
}
document.getElementById("second").onclick = function() {
document.getElementById("second").style.color = "pink";
}

Javascript pulling content from commented html

Bit of a JS newbie, I have a tracking script that reads the meta data of the page and places the right scripts on that page using this:
var element = document.querySelector('meta[name="tracking-title"]');
var content = element && element.getAttribute("content");
console.log(content)
This obviously posts the correct tag to console so I can make sure it's working .. and it does in a test situation. However, on the actual website the meta data i'm targeting is produced on the page by a Java application and beyond my control, the problem is it is in a commented out area. This script cannot read within a commented out area. ie
<!-- your tracking meta is here
<meta name="tracking-title" content="this-is-the-first-page">
Tracking finished -->
Any ideas appreciated.
You can use this code:
var html = document.querySelector('html');
var content;
function traverse(node) {
if (node.nodeType == 8) { // comment
var text = node.textContent.replace(/<!--|-->/g, '');
var frag = document.createDocumentFragment();
var div = document.createElement('div');
frag.appendChild(div);
div.innerHTML = text;
var element = div.querySelector('meta[name="tracking-title"]');
if (element) {
content = element.getAttribute("content");
}
}
var children = node.childNodes;
if (children.length) {
for (var i = 0; i < children.length; i++) {
traverse(children[i]);
}
}
}
traverse(html);
One way is to use a NodeIterator and get comment nodes. Quick example below. You will still need to parse the returned value for the data you want but I am sure you can extend this here to do what you want.
Fiddle: http://jsfiddle.net/AtheistP3ace/gfu791c5/
var commentedOutHTml = [];
var iterator = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT, NodeFilter.FILTER_ACCEPT, false);
var currentNode;
while (currentNode = iterator.nextNode()) {
commentedOutHTml.push(currentNode.nodeValue);
}
alert(commentedOutHTml.toString());
You can try this. This will require you to use jQuery however.
$(function() {
$("*").contents().filter(function(){
return this.nodeType == 8;
}).each(function(i, e){
alert(e.nodeValue);
});
});

Using one javascript code on multiple sections

I don't know much about jQuery but I've been using the following javascript code to make a table keep the scroll bar location upon pageback:
<script type="text/javascript">
window.onload = function () {
var strCook = document.cookie;
if (strCook.indexOf("!~") != 0) {
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS + 2, intE);
document.getElementById("grdWithScroll").scrollTop = strPos;
}
}
function SetDivPosition() {
var intY = document.getElementById("grdWithScroll").scrollTop;
document.cookie = "yPos=!~" + intY + "~!";
}
</script>
and
<div id="grdWithScroll" onscroll="SetDivPosition()">
It works great for a single div. But how could I extend this for use with a second div section?
Instead of using document.getElementById, you can asign the same class name to all the divs for which you want this functionality, and then user the jQuery selector $(".scrollgrid") to select the multiple divs, and store the scroll tops. If you do not want to use jQuery, you can look at the custom functions that people have written to select the elements by class name. Here is an example.
http://www.netlobo.com/javascript_getelementsbyclassname.html
Instead of a single div id, you could use class attribute to define all the divs you want the feature to be used on.
<div id="grdWithScroll" class="coolScroll" onscroll="SetDivPosition()">
</div>
<div id="abcWithScroll" class="coolScroll" onscroll="SetDivPosition()">
</div>
Use jQuery (or other libraries) to easily select all divs with said class and access the scrollTop attribute
$('.coolScroll').each( function()
{
// do something with scrollTop
}
You could also use the class selector to set the onscroll function.
$('.coolScroll').attr( 'onscroll' , 'javascript:SetDivPosition()' );
Found what I was looking for here:
http://social.msdn.microsoft.com/Forums/nb-NO/jscript/thread/ad18ed20-8ae2-4c13-9a51-dcb0b1397349
<script language="javascript" type="text/javascript">
//This function sets the scroll position of div to cookie.
function setScrollPos() {
var div1Y = document.getElementById('div1').scrollTop;
var div2Y = document.getElementById('div2').scrollTop;
document.cookie = "div1Pos=!*" + div1Y + "*!" +
" div2Pos=|*" + div2Y + "*|";
}
///Attaching a function on window.onload event.
window.onload = function () {
var strCook = document.cookie; if (strCook.indexOf("!~") != 0) {
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS + 2, intE);
document.body.scrollTop = strPos;
}
/// This condition will set scroll position of <div> 1.
if (strCook.indexOf("iv1Pos=!*") != 0) {
var intdS = strCook.indexOf("iv1Pos=!*");
var intdE = strCook.indexOf("*!");
var strdPos = strCook.substring(intdS + 9, intdE);
document.getElementById('div1').scrollTop = strdPos;
}
/// This condition will set scroll position of <div> 2.
if (strCook.indexOf("iv2Pos=!*") != 0) {
var intdS = strCook.indexOf("iv2Pos=|*");
var intdE = strCook.indexOf("*|");
var strdPos2 = strCook.substring(intdS + 9, intdE);
document.getElementById('div2').scrollTop = strdPos2;
}
}
</script>

Javascript - strikethrough

i try to make text strikethrough with javascript.
I know nothing about Javascript and try to search on the net how to that.
<script language="JavaScript">
function recal(val,sum)
{
if(sum == true)
{
var total = parseInt(document.getElementById("total").innerHTML, 10);
total+=val;
document.getElementById("total").innerHTML=total;
}
else
{
var total = parseInt(document.getElementById("total").innerHTML, 10);
total-=val;
document.getElementById("total").innerHTML=total;
var pnl = document.getElementById("totalEvents");
}
var pnl = document.getElementById("totalEvents");
var pnl2 = document.getElementById("eventCategory");
var pnl3 = document.getElementById("nameID");
**strikethrough starts here**
if (!sum && pnl.firstChild.tagName != "S" && pnl2.firstChild.tagname !="S")
{
pnl.innerHTML = "<S>"+ pnl.innerHTML+"</S>";
pnl2.innerHTML = "<S>"+ pnl2.innerHTML+"</S>";
}
else
{
pnl.innerHTML = pnl.firstChild.innerHTML;
pnl2.innerHTML = pnl2.firstChild.innerHTML;
}
}
</script>
it makes textstrikethrough but something is wrong. Even if i choose second checkbox it affects first checkbox why :(
http://jsfiddle.net/aHH9w/ (my full html page)
You are peforming a pretty convoluted way of achieving this, something that can actually be quite easily done. If you have an HTML element, say with the id 'myelement':
<div id="myelement">Hello world</div>
To create a strikethrough, all you need to do in JS is:
var ele = document.getElementById("myelement");
ele.style.setProperty("text-decoration", "line-through");
If you need to check if there is a strikethrough on an element:
var ele = document.getElementById("myelement");
var isStruck = (ele.style.getProperty("text-decoration") == "line-through");
Although this is not really recommended. Use an internal variable to keep track of state.

Greasemonkey - Find link and add another link

We have an internal inventory at work that is web based. I am looking at add a link say under a link on the page. There is no ID, or classes for me to hook into. Each link at least that I want to add something below it, starts with NFD. I basically need to pull the link text (not the link itself the text that appears to the end user) and use that in my url to call a web address for remoting in.
var links = document.evaluate("//a[contains(#href, 'NFD')]", document, null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i=0; i < links.snapshotLength; i++)
{
var thisLink = links.snapshotItem(i);
newElement = document.createElement("p");
newElement = innerHTML = ' Remote';
thisLink.parentNode.insertBefore(newElement, thisLink.nextSibling);
//thisLink.href += 'test.html';
}
Edit:
What I am looking for basically is I have a link NFDM0026 I am looking to add a link now below that using the text inside of the wickets so I want the NFDM0026 to make a custom link to call url using that. Like say a vnc viewer. The NFDM0026 changes of course to different names.
Here's how to do what you want (without jQuery; consider adding that wonderful library):
//--- Note that content search is case-sensitive.
var links = document.querySelectorAll ("a[href*='NFD']");
for (var J = links.length-1; J >= 0; --J) {
var thisLink = links[J];
var newElement = document.createElement ("p");
var newURL = thisLink.textContent.trim ();
newURL = 'http://YOUR_SITE/YOUR_URL/foo.asp?bar=' + newURL;
newElement.innerHTML = ' Remote';
InsertNodeAfter (newElement, thisLink);
}
function InsertNodeAfter (newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
parent.appendChild (newElement);
else
parent.insertBefore (newElement, targetElement.nextSibling);
}

Categories

Resources