Javascript access nested HTML element from given Javascript object argument - javascript

I am trying to write a small script that will automatically reveals/hides the content of a div when the mouse gets over/out of it. What I wanna do is to have the title visible and when someone mouseover the title some more text to get visible.
The problem is that I want to show/hide only a specific inner div of any given element and not to hide the entire element. I do have lots of elements so to handwrite javascripts for every single of them is a bit silly
My HTML code goes like:
<li id="job1" onmouseover ="div2mouseover(this)" onmouseout="div2mouseout(this)">
<div style = "display:none" id="jobDescription">
<p> Blablabla</p>
</div>
<li>
My JavaScript code goes like:
<script type="text/javascript">
function div2mouseover(obj)
{
//obj.style.display = "none"; //I can reach that
obj.getElementById("jobDescription").style.display = "initial"; //I can't reach that
}
</script>
So with the obj.style.display I can edit the visibility of any given element, but I can't reach its inner div that I am trying to reach.
I have managed to do that for a single element like this:
document.getElementById("jobDescription").style.display = "initial";
But with this way I have to write a script for all my job elements, which are a lot.
Any suggestions??

You can reference elements by their position too.
For example if the div you want to display is always the first div inside the "hover" li you can do
function div2mouseover(obj) {
var div = obj.getElementsByTagName("div")[0];
div.style.display = "initial";
}
You don't need any IDs in the divs if you do it like this.

The comment from the friend nnnnnn solved my case.. (maybe the other answers might work as well)
ID is supposed to be unique. Use a class instead, and use obj.querySelector(".classNameHere") – nnnnnn 12 mins ago
Thank you guys!

Related

Jquery put elements in div

You need to put items in a div - <div style = 'flex-direction: column;'>.
Div needs to be created after p withid = "billing_city_field"
and closes after the p withid = "apartment_field".
Tried to do it with this function:
jQuery (document) .ready (function ($) {
$ ("# billing_city_field"). after ("<div style = 'flex-direction: column;'>");
$ ("# apartment_field"). after ("</ div");
});
But the div immediately closes. What should I do?
The issue is because you cannot append start/end tags separately. The DOM works with elements as a whole, so you need to create the entire div element in a single operation.
Given the description of your goal it looks like you're trying to wrap the existing content in a new div. As such you can use nextUntil() (assuming the target elements are siblings) and then wrapAll(). Try this:
jQuery($ => {
let $contents = $("#billing_city_field").nextUntil('#apartment_field').add('#apartment_field');
$contents.wrapAll('<div class="column" />');
});
Note the use of a class attribute in the above example, instead of applying inline style rules.
Question is not super clear but from what I can tell.
I think you have small misunderstanding what .after does with jQuery. After in this case is "structural" and not "time" related. If you check jQuery docs (https://api.jquery.com/after/) for this you can see basically what you need to do.
Simplest way to do this, if these things needs to created and don't exist already on body for example.
$(function(){
var p = $("<p id='apartment_field'>Paragraph test</p>");
$("body").append("<div id='billing_city_field' style='flex-direction: column;'></div>");
$("#billing_city_field").html(p);
});
I've added Paragraph test so result is visible easier.
And one more thing, not sure if it's error with copy/paste but make sure that # and id don't have space in-between like this.
$("#billing_city_field")
$("#apartment_field")
Edit: Looking at the comments maybe something like this, if they exist already? You should clarify the question more.
$("#billing_city_field").append($("#apartment_field").detach());

How to swap placement of two elements, including their classes/ids with onclick?

I'm trying to switch the positions of two divs with an onclick event.
The divs have the same basic format (width, height), but an additional class and id change the way they look.
So, I have two functions that successfully change the id and class names, but there is no visual change.
Here they are:
function whenClickedFilled(){
console.log("filled");
this.firstElementChild.id = "empty";
this.firstElementChild.className = "puzzlepiece emptyDivClass";
}
function whenClickedEmpty(){
console.log("empty");
this.firstElementChild.id = "filled";
this.firstElementChild.className = "puzzlepiece";
}
I'd like to know what the best way is to alternate between classes/ids onclick.
Here is my js fiddle.
I think what you're really looking to do is not swaping the class and id, but swap the elements themselves. This will make sure the numbers contained within the div's is also transfer with the swap.
You still need to implement the logic checks to see if the element should be able to swap with the empty block and there looks like theres a bug when you click empty space itself. But, this should get you on the right track. I recommend placing a debugger statement to step through the code with dev tools open. It will help understand whats taking place. Good luck.
function whenClickedFilled(){
console.log("filled");
//Get the div element and parent
//Then determine the parent of the empty div
var clickedDiv = this.firstChild; //this refers to the TD clicked, get the child div element
var clickedDivParent = this; //this is TD
var emptyDivParent = emptyDiv.parentElement; //stored the empty div reference into a global, retrieve the parent as this could change
//Remove the empty and clicked div's from their container
emptyDivParent.removeChild(emptyDiv)
clickedDivParent.removeChild(clickedDiv);
//Add the elements back to the containers but swapped
clickedDivParent.appendChild(emptyDiv);
emptyDivParent.appendChild(clickedDiv);
}
http://jsfiddle.net/tWrD2/
I'm trying to switch the positions of two divs with an onclick event
If you want to swap two adjacent nodes, you can do something as simple as:
function swapAdjacent(el0, el1) {
el0.parentNode.insertBefore(el1, el0);
}
If you want to swap any two elements in the DOM, you can do something like:
// Swap the postion in the DOM of el0 and el1
function swapElements(el0, el1) {
// Create a temp node that can replace el0
var tmp = el0.cloneNode(false);
// Replace el0 with tmp
el0.parentNode.replaceChild(tmp, el0);
// Replace el1 with el0
el1.parentNode.replaceChild(el0, el1);
// Replace temp node with el1
tmp.parentNode.replaceChild(el1, tmp);
}
and some test markup:
<div id="d0">div 0</div>
<div id="d1">div 1</div>
<button onclick="
swapElements(document.getElementById('d0'), document.getElementById('d1'));
">Swap d0, d1</button>
<button onclick="
swapAdjacent(document.getElementById('d0'), document.getElementById('d1'));
">Swap adjacent</button>
Of course the two elements to swap must be consistent with the surrounding elements, e.g. you can't swap an option element with a div and expect everything to work, but you can probably swap a span with a div.
If you want to swap elements by clicking on one or the other:
<div id="d0" onclick="swapElements(this, document.getElementById('d1'))">div 0</div>
<div id="d1" onclick="swapElements(this, document.getElementById('d0'))">div 1</div>
I found a nice solution provided by fuell when I was searching fo an actual html swap:
<div id="div_1">THIS IS DIV 1</div>
<div id="div_2">THIS IS DIV 2</div>
Go Swap!
$(document).ready(function() {
$(".go-swap").click(function() {
$("#div_1").removeAttr("style");
$("#div_2").removeAttr("style");
var tmp = $("#div_1").html();
$("#div_1").empty().append($("#div_2").html());
$("#div_2").empty().append(tmp);
});
});

How to access the sibbling node of parent in javascript?

I have various questions on my faq page like this
<h3>How to signup?</h3>
<div class="info" style="display:none">
This is the hidden answer
</div>
The answer is hidden and when the user clicks on the link the div below it appears.Though I can do this using jquery easily but I don't want to make the page heavy so I simply using the following function
function toggle_display()
{
var answers=document.getElementsByClassName("info");
for(var i=0;i<answers.length;i++)
{
//hide all the divs first
answers[i].style.display='none';
}
//return block as style so that the caller's div answer can be set to block
return 'block';
}
But I am having problem accessing the next sibbling div of the link.What should I substitute in the following line
<a href="#" onclick="**this.parent.nextSibbling**.style=toggle_display()">
If you want to get the next sibling of parent node then your code should be like this.
this.parentNode.nextSibling
For ignoring text dom nodes and get the right one element use:
this.parentElement.nextElementSibling.style = ......

Accessing elements inside dynamically created divs with HTML/Javascript

I'm quite new to javascript and JQuery programming. Usually, to access elements I give them an id, so I can get them like $("#"+id).blabla().
But now I need to dynamically create a div, and access elements inside it.
Something like
<div id="automaticallyGeneratedId">
<div ???></div> <!-- first div -->
<div ???></div> <!-- second div -->
</div>
What are the best practices to access and identify each of the inner divs?
I generate another id for them?
Or what?
I don't have the theory of selectors fully clear.
edit: modified the question from identifying a single inner div to identifying divs amongs many of them
You can maintain a pattern when you're generating id. For example:
if you always generate id like: myid1, myid2,myid3...
<div id="myid1">
<div></div>
</div>
<div id="myid2">
<div></div>
</div>
......
then you can try:
$('div[id^=myid]').find('div').foo();
OR
$('div[id^=myid] div').foo();
Here, ^= is start with selector, so div[id^=myid] will select div whose id start with myid.
You can also use Contain word selector which is ~= and use like $('div[id~=myid]'). This will select div with id contains word myid.
Instead of id if you want to use other attribute eg. name then change selector like:
$('div[name^=myid]') or $('div[name~=myid]').
It's usually a good practice that if you already have a reference to that outer div to just search from there using find.
You can give it an id, or if you want to use a more general approach you can use classes.
<div class="subdiv">...
$('#automaticallyGeneratedId').find('div.subdiv')
Usually, when you create them, you can assign event handlers and the likes straight on them. Like this:
var div = $( '<div></div>' );
div.on( 'click', function() {
// Do something when the generated div is clicked
});
// Then, add it to the DOM
$( 'body' ).append( div );
You don't need to bother selecting them with ID or classes, they're already available in your code.
Another way is to use event bubbling to handle newly created elements of the same class. A good link about this is this one: http://beneverard.co.uk/blog/understanding-event-delegation/
Many ways you can create an element and give him an Id or Class, or use the DOM to access it..
$("html").prepend('<div id="foo"></div>');
$("#foo").doSomething();
another way
$("#automaticallyGeneratedId").find("div").doSomething();
To access the div in the element with the id:
$("#automaticallyGeneratedId div").whatever
If you cache the divs you could use something like:
var myDiv1Child = $('div', myDiv1);
Create a delegated listener and within the listener you can find the element by doing this
//If a div inside the parent is clicked then execute the function within
$('.PARENT_CLASS').click("div", function(){
//This variable holds all the elements within the div
var rows = document.querySelector('.PARENT_CLASS').getElementsByTagName('div');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
console.log(this); //The element you wish to manipulate
}
}
});

javascript get child by id

<div onclick="test(this)">
Test
<div id="child">child</div>
</div>
I want to change the style of the child div when the parent div is clicked. How do I reference it? I would like to be able to reference it by ID as the the html in the parent div could change and the child won't be the first child etc.
function test(el){
el.childNode["child"].style.display = "none";
}
Something like that, where I can reference the child node by id and set the style of it.
Thanks.
EDIT: Point taken with IDs needing to be unique. So let me revise my question a little. I would hate to have to create unique IDs for every element that gets added to the page. The parent div is added dynamically. (sort of like a page notes system). And then there is this child div. I would like to be able to do something like this: el.getElementsByName("options").item(0).style.display = "block";
If I replace el with document, it works fine, but it doesn't to every "options" child div on the page. Whereas, I want to be able to click the parent div, and have the child div do something (like go away for example).
If I have to dynamically create a million (exaggerated) div IDs, I will, but I would rather not. Any ideas?
In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():
function test(el){
el.querySelector("#child").style.display = "none";
}
For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.
As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").
This works well:
function test(el){
el.childNodes.item("child").style.display = "none";
}
If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.
If the child is always going to be a specific tag then you could do it like this
function test(el)
{
var children = el.getElementsByTagName('div');// any tag could be used here..
for(var i = 0; i< children.length;i++)
{
if (children[i].getAttribute('id') == 'child') // any attribute could be used here
{
// do what ever you want with the element..
// children[i] holds the element at the moment..
}
}
}
document.getElementById('child') should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.
edit : see this page - ids MUST be unique.
edit edit : alternate way to solve the problem :
<div onclick="test('child1')">
Test
<div id="child1">child</div>
</div>
then you just need the test() function to look up the element by id that you passed in.
If you want to find specific child DOM element use method querySelectorAll
var $form = document.getElementById("contactFrm");
in $form variable we can search which child element we want :)
For more details about how to use querySelectorAll check this page

Categories

Resources