get outer div by id, then get inner div by class - javascript

First I want to get the outer div by id, then the inner div by class (dynamically added by jquery mobile ui-collapsible content) and finally append a child text node to it.
<div id="aab" data-role="collapsible" data-content-theme="c">
<h3>Heading</h3>
<div class="ui-collapsible-content">
<div id="coll">
Collapsible Content
</div>
</div>
</div>
<p><button onclick='func()'>Button</button></p>
<script>
function func() {
var section = $("#aab > .ui-collapsible-content");
section.appendChild(document.createTextNode("Hello world!"));
}
</script>
I also tried things out with document.getElementById but somehow it doesn't work.. Thanks in advance!

You have use jquery for selection so you should use it for adding child
function func() {
var section = $("#aab > .ui-collapsible-content");
section.append("Hello world!");
}

Related

jQuery select another element with certain class in same parent

let say i have this div
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>
I wanted to give the #button an on click event that returned the text at #lookAtMe div, specific to the div whom it shares parent/grandparent (in this case, the #parent div)
I tried using:
$("#button").on("click",function(){
var ReturnedText = $(this).parent(".lookAtMe").text();
console.log(RetrunedText);
});
But the console log would retruned (empty string).
Where did i do wrong? please help. Thankyou very much.
Because there is n o parent with that class. You need find().
Actually you need to write
var ReturnedText = $(this).parent().find(".lookAtMe").text();
$("#button").on("click",function(){
var ReturnedText = $(this).parent().find(".lookAtMe").text();
console.log(ReturnedText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>

Show and append a div

I'm writing a HTML code where there are 3 divs - and in the mainDiv2, there is this another div that is hidden. When I click on the mainDiv2, I want to unhide the hiddenDiv(this I'm able to do it). As well as I want this hiddenDiv to be shown in mainDiv1 as a child.
Here is my code.
<div class="mainDiv1">
This si a main div content
</div>
<div class="mainDiv2" onclick="showhiddenDiv()">
This is a sub div content
<div class="hiddenDiv" id="hiddenDiv" style="display:none">
Hello World
</div>
</div>
JS
function showhiddenDiv(){
document.getElementById('hiddenDiv').style.display="block";
}
please let me know how can I do this.
Here is a working fiddle. https://jsfiddle.net/8pj3uvfn/1/
Thanks
You can use appendChild like below
function showhiddenDiv() {
var hiddenDiv = document.getElementById('hiddenDiv');
var mainDiv1 = document.getElementsByClassName('mainDiv1')[0];
hiddenDiv.style.display = "block"
mainDiv1.appendChild(hiddenDiv)
}
<div class="mainDiv1" id="mainDiv1">
This is a main div content
</div>
<div class="mainDiv2" onclick="showhiddenDiv()">
This is a sub div content
<div class="hiddenDiv" id="hiddenDiv" style="display:none">
Hello World
</div>
</div>
As well as I want this hiddenDiv to be shown in mainDiv1 as a child.
You need to clone the hiddenDiv and put it in mainDiv1.
So modify your method as
function showhiddenDiv(){
var hiddenNode = document.getElementById('hiddenDiv');
hiddenNode.style.display="block";
var copyHiddenNode = hiddenNode.cloneNode( true );
copyHiddenNode.id += "_1"; //change the id so that ids are not duplicated
document.getElementById("mainDiv1").appendChild( copyHiddenNode );
}
You could use appendChild
function showhiddenDiv(){
var hiddenDiv = document.getElementById('hiddenDiv');
document.getElementsByClassName('mainDiv1')[0].appendChild(hiddenDiv);
hiddenDiv.style.display="block";
}
Demo
Assuming that you have set the id attributes of the divs properly,
function showhiddenDiv(){
var hiddenDiv = document.getElementById('hiddenDiv'); //Get the reference
document.getElementById('mainDiv1').appendChild(hiddenDiv) //Chenge the DOM order (you don't have to clone)
hiddenDiv.style.display="block"; //Unhide
}
<div class="mainDiv1">
This si a main div content
</div>
<div class="mainDiv2" onclick="document.getElementById('hiddenDiv').style.display = 'block'">
This is a sub div content
<div class="hiddenDiv" id="hiddenDiv" style="display:none">
Hello World
</div>
</div>

Get next element with a class name without using jquery

I do not have access to jquery. I'm trying to implement an accordion, but the content element is not immediately after the header. It is something similar to the following:
<div class="header">...</div>
<div>
<div class="content">
So I'm adding a function to handle an onclick event on the header, which needs to then obtain the next element in the HTML source code that has the content class. How can I achieve that?
You can achieve this using querySlector on the clicked header node
<div class="header">
<div>
<div class="content">
[].forEach.call(document.querySelectorAll('.header'), function(header) {
header.addEventListener('click', function(e) {
var content = this.querySelector('.content');
// here, "this" is the header div, and "content" is the content div
// do majick accordion things here
});
});
How about using recursive function and nextSibling [get next element (not children)]
<div class="header" onclick="hasClass(this)">...</div>
<div>
<div class="content"></div>
</div>
<script>
function hasClass(e){
if(e.nextSibling.children === undefined || e.nextSibling.children.length == 0){
hasClass(e.nextSibling); //go next till find class
}
else{
if(e.nextSibling.children[0].className == "content"){
console.log(e.nextSibling.innerHTML); //get class content html
}
}
}
</script>
You can get this by
var contentDiv= document.getElementsByClassName("content");
try this document.getElementById(header).getElementsByClassName('content');

jQuery how to replace all contents of an element into another?

Say I have 3 elements like below with different html contents:
<div id='result1'> <p>One</p> </div>
<div id='result2'> <p>Two</p> </div>
<div id='result3'> <p>Three</p> </div>
How can I copy just contents within the div element to the next one so that the final result looks like this?
<div id='result1'> <p>New content</p> </div>
<div id='result2'> <p>One</p> </div>
<div id='result3'> <p>Two</p> </div>
There will be new content for replacement and the last content can be discarded.
To clarify, I'll have something like:
<div id='new'> <p>New content</p> </div>
where I want to grab '<p>New content</p>' as new content to use.
What do you think?
To push the content down, reverse the collection and set the HTML to the HTML of the previous one.
var elems = $($('[id^=result]').get().reverse());
elems.html(function(i) {
return elems.eq(i+1).html();
}).last().html('New Content');
FIDDLE
You can use .html() on the element you want to change the content. For accessing particular element you can use ID Selector (“#id”) with Child Selector (“parent > child”).
Live Demo
$('#result1 > p').html('New content');
Edit to move contents to next elements you can iterate through all elements and start assigning the context of second last to last, third last to second last and so on
Live Demo
elements = $('[id^=result] > p');
len = elements.length;
elements.each(function(idx, el){
if(idx == elements.length-1) return;
$('#result'+ (len-idx) + ' p').html($('#result' + (len-idx-1) + ' p').html());
});
$('#result1 > p').html('New content');
try JS fiddle
I am suggesting to add a Parent Grid and use jquery first() and last(), These controls will function like a queue.
$('#Pdiv').children().last().remove();
$('#Pdiv').first().prepend("<div id='new'> <p>I am New One</p></div>");
alert($('#Pdiv').children().first().html());

How do I use a function argument for this jquery code, or is there a better solution?

I have about 50 p tags and next to these are again 50 divs. on click of each p tag, its div should be shown and the rest hidden. How do i acheive this. I can use something like below:
$(function() {
$('.p1').click(function(){
$('.div1').show();
$('.div2','.div3','.div4','.div5','.div6',.........,'.div50').hide()
})
$('.p2').click(function(){
$('.div2').show();
$('.div1','.div3','.div4','.div5','.div6',.........,'.div50').hide()
})
//////////////
//////
})
but as you see that this is not an effiecient solution. I am also not sure how the jquery each can be leveraged here or how can this implementation be done using arrays. Can somebody point me in the right direction. I think we should use a function and pass that no. as a parameter, but I dont know how to use custom functions in jquery.
UPDATE:
This is what I have done
$(function() {
$('.p1').click(function() {
$('.div').hide();
$('.d1').show();
})
})
I have added the class div to all of my 50 divs and I am showing d1 on click of p1. Now how do I replace 1 for each instance till 50.
I would have a common class to all div and p so that the binding the handler and the hide can be simple. And for the div, I would associate a data-tag to each p to link each p tag to div
<p class="p1 pclass" data-showdiv="div1">
...
</p>
<p class="p2 pclass" data-showdiv="div2">
..
<div class="mydiv div1" ..>
..
</div>
<div class="mydiv div2" ..>
..
</div>
And the script would be,
$(function() {
$('.pclass').click(function(){
$('.mydiv').hide();
$('.' + $(this).data('showdiv')).show();
});
});
As Jason told,
Use this
$('p').click(function() {
$('div').hide();
$(this).next('div').show();
});
If the div is next to each paragraph.
But, if there's an element between p and div, it wont work.
For you problem, you can do,
$('p').click(function() {
$('div').hide();
var divClass = $(this).attr("class").replace('p','div');
$('.' + divClass).show();
});
provided you have only p1, p2 .... in paragrah classes ;)
Update
See this fiddle
Notice , we have <br> tags between <p> and <div> as you wanted.
Assuming your HTML structure is
<p>Some text</p>
<div>More text to hide and show</div>
<p>Some text</p>
<div>More text to hide and show</div>
<p>Some text</p>
<div>More text to hide and show</div>
....
Use the following in your $(function(){}); method:
$('p').click(function() {
$('div').hide();
$(this).next('div').show();
});
var dvs = ['.div1','.div2','.div3','.div4','.div5','.div6',.........,'.div50'];
$('p').click(function() {
var index = parseInt(this.className.replace('p','')) - 1;
$(dvs[index]).show();
$(dvs.join(', ')).not(dvs[index]).hide();
});
The jQuery click event will automatically be registered on all elements that match the selector, so you shouldn't have to use the each() method. I would suggest having two CSS classes to distinguish between elements that have this toggling behaviour and elements that are primary (i.e. should be shown when their parent is clicked).
The markup:
<body>
<p class="togglable">
<div class="primary">
This is the primary div that will be shown when our parent is clicked.
</div>
<div>Regular div child</div>
<p>Nested paragraph</p>
<ul>
<li>A list perhaps</li>
</ul>
</p>
<p class="togglable">
<div class="primary">
This is the primary div that will be shown when our parent is clicked.
</div>
<div>Regular div child</div>
<p>Nested paragraph</p>
<ul>
<li>A list perhaps</li>
</ul>
</p>
<p>This is a normal paragraph</p>
</body>
The code:
$(function () {
$('.togglable').click(function () {
// hide all our children
$(this).children().hide();
// now only show our primary chlid
// NOTE: we pass 'this' as the second argument
// so that the selector will only apply to the
// children of the element that was clicked
// (i.e. we are providing a custom context for the selector).
$('.primary', this).show();
// You could even use the position of the child as well:
// $(this).children().first().show();
// This will show the first child element.
});
});
In this example all elements with the class togglable will show their primary child element when clicked and hide all other child elements.

Categories