how to target an external div in javascript - javascript

I have this situation:
<div id="first">
<div>
<p>text</p>
</div>
</div>
<div id="second">
<div>
<button class="button">click</button>
</div>
</div>
...
<div id="first"> ... </div>
<div id="second"> ... </div>
...
and so on, the structure repeats.
This structure is created dynamically so I can't use any specific class nor id for the first div.
I need to retrieve the text in the first div when I hit the button in the second div.
(NOTE: I need a pure javascript solution, not a jQuery solution)
Thanks

Assuming you have an event handler for the button click, you could do this from that event handler:
function buttonClickHandler(e) {
var first = this.parentNode.parentNode.previousSibling;
var paragraphs = first.getElementsByTagName("p");
var text = paragraphs[0].textContent;
}
If you have common and known class names on the the divs marked first and second, then you can make your Javascript code much more insulated from markup changes which is generally a good idea.
P.S. I presume you know that you should't have duplicate id values in your HTML. This code doesn't use them, but you should be using class names instead of id values if you're going to have duplicates.

Related

JavaScript/jQuery detect if div contains text excluding children

I need to verify if a DIV has some text or not inside of it BUT NOT inside its children, eg see this example
<div id='one'>
<div id='two'>Abc</div>
</div>
<div id='three'>xyz
<div id='four'></div>
</div>
If I hover/click element one I want to get false (no text), but if i hover element three I want to get true
i tried using
$('#one').text().trim().length > 0
but it seems to check also any children which is want I do not want to happen
This is already answered here: jquery - get text for element without children text
Also mentions using a plugin to accomplish getting only the text of the element and not child elements here: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/
This meets your requirements
window.onload=function(){
var two = document.getElementById('two').textContent;
console.log(two.trim()=='');
var three = document.getElementById('three').textContent;
console.log(three.trim()=='');
}
<div id='one'>
<div id='two'>Abc</div>
</div>
<div id='three'>
<div id='four'></div>
</div>

Clone Div into another DIV

I am trying to clone a DIV to prevent data reputation; this is a frequent thing I want to do over various pages so I don't want to make bug structural changes.
I would like to Clone mApageLeft with the class maContent, and all of its inner div's and content into another div named cloneContent.
I have looked at other examples of Clone, and my attempt does not show anything. Thanks in advance for any help.
<div>
<div>
<div>
<div id="mApageLeft" name="mApageLeft" class="maContent">
<div> header and some text here
</div>
<div> text and image here
</div>
<div> text and another image here
</div>
</div>
</div>
</div>
</div>
<div id="mobileArea">
<div id="mobileMainArea">
headers, links and sme text
<div name="cloneContent" id="cloneContent" class="maContent"></div>
<script>
$(function(){
var $mainAreaClone = $('#mApageLeft').clone();
$('#cloneContent').html($mainAreaClone);
});
</script>
</div>
</div>
Your code works fine when I test it on fiddle. Even after that, if you wanna try something else, you can try append() instead of html() function. Usually when you clone, you want to append the cloned object, you don't want to put is as inner HTML. However, that will also work.

Hiding many divs with one onclick function

I am looking for a Javascript solution for this problem. I have the following HTML:
<div id = "container">
<div id = "data">
<div>
<h3> Address</h3>
<b>Expand...</b>
<div id="content">ul. Pomorska</div>
</div>
<div>
<h3> Telefon </h3> <b>Expand...</b>
<div id="content">26565352</div>
</div>
<div>
<h3>Email</h3>
<b>Expand...</b>
<div id="content">asdasdag#aga.com</div>
</div>
</div>
</div>
I would like to hide the content div when an onclick Expand is made. So far I have made a function which hides the content divs and tries to assign an event handler to the node.
function hideinfo() {
var node = document.getElementById("data");
var contactdata = node.getElementsByTagName("div");
for(var i=0; i<contactdata.length;i++) {
if(contactdata[i].id == "content") {
alert(contactdata[i].previousSibling.innerHTML);
contactdata[i].previousSibling.addEventListener('click',ShowHide,false);
contactdata[i].style.display="none";
}
}
}
The problem is that the alert displays undefined. Why can't it see the node? Is there a better way to do this in Javascript?
Because previousSibling is most likely the text node before the div element. You probably want to use previousElementSibling instead :)
In most browser today, querySelectorAll, which lets you use CSS selectors for finding elements, is also a good alternative (IE8+)
The previousSibling property returns the previous sibling node (the previous node in the same tree level) of the selected element
which returns in your case the TEXT node.
As you can see in this jsfiddle: http://jsfiddle.net/Xu383/
alert(contactdata[i].previousSibling.nodeName);
You are better of using the querySelectorAll.
Also you can't have multiple divs with the SAME id, use class instead.

Clear text inside DIV

I'm using the following HTML structure:
<div id="clock">5:30 AM
<div id="day">Wednesday
</div>
<div id="date">14 December
</div>
</div>
I update the contents of these elements using Javascript. For "day" and "date" I use $("#day").text(day) and $("#date").text(date). Because "clock" is a parent element I had to use $("#clock").prepend(clock) to succesfully add the text.
The problem with the latter function, is that new text is prepended every time the clock is refreshed, i.e. it builds up a list of clock times. For the first two functions the text is just replaced, like it should. Is there a way to make this happen for the "clock" function as well?
EDIT: Sorry, should have been a bit more clear about the clock. Have edited the code, so you understand. BTW, the reason the clock is parent element is that could make the other two elements depend on the clock's position and styling.
I also created a jsFiddle: https://jsfiddle.net/daanodinot/NZtFA/
I left the list building thing (annoyingly) in!
BTW, I'm not too sure if function(); setInterval('function()', 1000) is the best way to refresh, so if you something better I'd be happy to know :)
What you need to do is change the structure of your html to this.
<div id="wrapper">
<div id="clock"></div>
<div id="day"></div>
<div id="date"></div>
</div>
Then for the javascript
$('#clock').text('12:45');
$('#day').text('Wednesday');
$('#date').text('12/14/2011');
This way you can just change/refresh the text of clock instead of prepending values to it.
Another approach, with your current html, which i do not recommend.
<div id="clock">
<div id="day">
</div>
<div id="date">
</div>
</div>
The js
$('#clock').contents().get(0).nodeValue = '12:45';
$('#day').text('Wednesday');
$('#date').text('12/14/2011');
If you have HTML
<div id="clock">
<div id="day"></div>
<div id="date"></div>
</div>
Then you don't have to modify #clock at all. By doing $("#day").text(day) and $("#date").text(date) content of those divs is changed and you don't have to touch #clock.
But in case you want to replace a content of a element then use .html(newContent). See documentation.
You should first add a new element with prepend and then replace it's content, now you just constantly keep prepending new elements instead of working on the same element again.
What do you mean by
Because "clock" is a parent element I had to use
$("#clock").prepend(clock) to succesfully add the text.
?
It seems redundant. Since $('#day') and $('#date') uniquely address your targeted elements.
My tip:
Do not use clock. $("#day").text(day) and $("#date").text(date) already update the numbers inside your #clock element.
Hy,
my consideration for your problem is, IF you choose to manipulate the Content of the #clock div you could simply do this:
var newContent="";//in here comes whatever you want to add to your clock div
$('#clock').html($('#clock').html()+newContent);
That's the way I use it most of the time but you could also do this:
var curContent=$('#clock').html();
curContent+="<>put in your code to add</>";
$('#clock').html(curContent);
This is I guess a bit slower than the first one, but it works.

jQuery: get a reference to a specific element without using id

I'm tinkering a bit with jquery to show a hidden div when a link is clicked. This should be fairly simple, but there's a flaw to it in this case. I have the following markup:
<div class="first-row">
<div class="week">
<p>Uge 2</p>
<p>(08-01-11)</p>
</div>
<div class="destination">
<p>Les Menuires</p>
<p>(Frankrig)</p>
</div>
<div class="days">4</div>
<div class="transport">Bil</div>
<div class="lift-card">3 dage</div>
<div class="accommodation">
<p><a class="show-info" href="#">Hotel Christelles (halvpension)</a></p>
<p>4-pers. værelse m. bad/toilet</p>
</div>
<div class="order">
<p>2149,-</p>
<p class="old-price">2249,-</p>
</div>
<div class="hotel-info">
<!-- The div I want to display on click -->
</div>
</div>
When I click the "show-info" link I want the "hotel-info" div to display.
My backend devs don't want me to use ids (don't ask me why..) and the above markup is used over and over again to display data. Therefore I need to be able to access the "hotel-info" div in the "first-row" div where the link is clicked.
I've tried to do something like:
$(document).ready(function() {
$('.show-info').click(function() {
var parentElement = $(this).parent().parent();
var lastElementOfParent = parentElement.find(".show-hotel");
lastElementOfParent.show();
});
});
But without a result :-/ Is this possible at all?
Any help is greatly appreciated!
Thanks a lot in advance!
Try this:
$('.show-info').click(function() {
$(this).closest('.accommodation').siblings('.hotel-info').show();
});
Even better imo, as it would be independent from where the link is in a row, if every "row div" has the same class (I assume only the first one has class first-row), you can do:
$(this).closest('.row-class').find('.hotel-info').show();
Reference: .closest, .siblings
Explanation why your code does not work:
$(this).parent().parent();
gives you the div with class .accommodation and this one has no descendant with class .hotel-info.
It is not a good idea to use this kind of traversal for more than one level anyway. If the structure is changed a bit, your code will break. Always try to use methods that won't break on structure changes.
You're right in not using an ID element to find the DIV you want :)
Use closest and nextAll
Live demo here : http://jsfiddle.net/jomanlk/xTWzn/
$('.show-info').click(function(){
$(this).closest('.accommodation').nextAll('.hotel-info').toggle();
});

Categories