How to access appended element and remove it? - javascript

I've done quite a bit of research for this but can't get my mind around it.
There is a parent div .container. Which has numerous child divs having different text inside them. There are two buttons outside the .container. One is used to dynamically create and append a child element having particular text. Other is to remove a child div having particular text.
The first time the page is loaded everything works but when a new child div is added (lets say having text xyz) and then use enters xyz in textarea and presses remove button (which is coded to remove child div having text xyz in them) it doesn't work.
Sample HTML markup (there may be infinite number of child divs)
<div class="container>
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
<div class="child4"></div>
</div>
<button class="AppendWithSomeText"></button>
<button class="RemoveDivWithSomeMatchedText"></button>
<textarea></textarea>
jquery for adding the div
var newdiv = = document.createElement('div');
newdiv.className = 'child';
$(".container").append(newdiv);
$(".container").find(".child").html(textfromtextarea);
// here text from text area is a string stored from user input in textarea
jQuery for remove button
$('.container>div:contains("'+textfromtextarea+'")').remove();
//works only first time

http://codepen.io/dustinpoissant/pen/VYXGwB
HTML
<input type='text' id='input' />
<button onclick='addItem()'>Add</button>
<button onclick='removeItem()'>Remove</button>
<br><br>
<div id='box'></div>
JavaScript
function addItem(){
$("#box").append("<span>"+$("#input").val();+"</span>");
}
function removeItem(){
var text = $("#input").val();
$("#box span").each(function(i, el){
if($(el).text()==text) $(el).remove();
});
}

Inorder to keep the uniformity of structure I have added class of type child-number.
I hope this is what you expected.
$(document).ready(function() {
$(".AppendWithSomeText").on("click", function() {
$(".container").append("<div class=child" + ($("[class^='child']").length + 1) + ">" + $(".content").val() + "</div>")
})
$(".RemoveDivWithSomeMatchedText").on("click", function() {
$('.container>div:contains("' + $(".content").val() + '")').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<div class="child1">somecontent</div>
<div class="child2">somecontent</div>
<div class="child3">somecontent</div>
<div class="child4">somecontent</div>
</div>
<button class="AppendWithSomeText">add</button>
<button class="RemoveDivWithSomeMatchedText">remove</button>
<textarea class="content"></textarea>

Related

Move closing </a> tag to the end of a containing element

I'm trying to get a link to wrap around all text within a div. I can only find solutions where you move certain DOM elements entirely, or move other elements into an element.
current situation:
<div class="text">
text and more text
</div>
desired situation:
<div class="text">
text and more text
</div>
Unfortunately, I cannot change the markup, so I have to do something with jQuery.
Avoid messing with html directly, it's better not to change it or overwrite. All you need to do is to take next text sibling Node and append to previous a:
$('.text a').each(function() {
$(this).append(this.nextSibling)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text">
text and more text
</div>
If necessary you can check for the next node to be TextNode, if you need to skip element nodes:
if (this.nextSibling.nodeType === 3) {
$(this).append(this.nextSibling)
}
You need to use .append( function ) to insert nextSibling of anchor into it.
$(".text a").append(function(){
return this.nextSibling
});
$(".text a").append(function(){
return this.nextSibling
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text">
text and more text
</div>
Also you can use .html( function ) instead and then remove next sibling using .remove()
$(".text a").html(function(i, h){
return h + this.nextSibling.nodeValue;
})[0].nextSibling.remove();
Or in one line using ES6
$(".text a").html((i,h) => h+this.nextSibling.nodeValue)[0].nextSibling.remove();
$(".text a").html(function(i, h){
return h + this.nextSibling.nodeValue;
})[0].nextSibling.remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text">
text and more text
</div>
Or using pure javascript
var ele = document.querySelector(".text a");
ele.innerHTML += ele.nextSibling.nodeValue;
ele.nextSibling.remove();
var ele = document.querySelector(".text a");
ele.innerHTML += ele.nextSibling.nodeValue;
ele.nextSibling.remove();
<div class="text">
text and more text
</div>
HTML/JavaScript doesn't work in a way that you can "move" a closing tag like that, but what you can do is move the text. Also, you don't need jQuery to do it; it's very easy to do with vanilla JavaScript:
let link = document.querySelector('.text a')
let textAfterLink = link.nextSibling
link.appendChild(textAfterLink)
<div class="text">
text and more text
</div>
You can first get the HTML inside the div with class text and then replace the closing tag </a> with '' then finally append a closing </a> tag to the replaced string so that you get what you expect:
var aHTML = $('.text').html();
aHTML = aHTML.trim().replace(/<\/a>/, '') + '</a>';
$('.text').html(aHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text">
text and more text
</div>
Here you have one approach that will find all unwraped text inside the element with class .text and append all of these texts to the first <a> child. This approach uses the content() method chained with a filter() using the addequated condition for remove the texts children, while at the same time they are appended to the <a> element.
$('.text').each(function()
{
$(this).contents().filter(function()
{
// Filter text type only.
return (this.nodeType === 3);
})
.appendTo($(this).find("a:first-child"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text">
text and more text
</div>
<hr>
<div class="text">
Rise up this morning
Smile with the rising sun
<br>
Three little birds
<br>
Pitched by my doorstep
<br>
<p>DON'T TOUCH THIS ONE!</p>
Singing sweet songs
<br>
Of melodies pure and true
<br>
Sayin': This is my message to you
<br>
Saying, don't worry about a thing
<br>
'Cause every little thing
<br>
Gonna be all right
</div>

AppendChild a element above a cerain element

So i have a div element which will be filled dynamically with others divs using the appendChild Method, this should display a list. The User is now able to sort that list with the JqueryUI Sortable option.I also added some sortable option attribues like follows:
Options:
$("#NameContainer").sortable("option", "axis", "y");
$("#NameContainer").sortable( "option", "containment", "parent" );
LIST
<div id="NameContainer" class="ui-widget">
<div id="Name_1">John</div>
<div id="Name_2">Jack</div>
<div id="Name_3">Charlie</div>
<div id="Name_4">Sawyer</div>
<div id="Name_5">Yin</div>
<div id="Name_6">Ben</div>
</div>
Now comes my problem. The appendChild always inserts the new div at the bottom of the container but i want to to add some space at the bottom of to the Container Div with a "br" or something like that. I want to add that space to make sure that when the user sorts the last item of that list it will get sorted correctly because the "containment" bounds sometimes wont allow to sort under the last item.
<div id="NameContainer" class="ui-widget">
<div id="Name_1">John</div>
<div id="Name_2">Jack</div>
<div id="Name_3">Charlie</div>
<div id="Name_4">Sawyer</div>
<div id="Name_5">Yin</div>
<div id="Name_6">Ben</div>
<br><!--SPACEHOLDER-->
</div>
So here comes my Question is there away to appendChild above a certain element? Like a "br" "div" or "p"?
Try this instead of appendChild:
Please note I have used random value to add in div as I don't have your dynamic value.
check fiddle: https://jsfiddle.net/dqx9nbcy/
<div id="NameContainer" class="ui-widget">
<div id="divspacer"></div>
</div>
<button id="btn">ADD Element</button>
$(document).ready(function(){
$("#btn").click(function(){
var parentnode = document.getElementById("NameContainer");
var existnode = document.getElementById("divspacer");
var rand = Math.floor((Math.random() * 10) + 1);
var newName = document.createElement("div");
newName.setAttribute("id", rand);
newName.setAttribute("value", rand);
newName.setAttribute("class","ui-widget-content");
newName.innerHTML = rand;
parentnode.insertBefore(newName,existnode);
});
});
refer http://api.jquery.com/appendto/ but you need to make sure that your are targeting right tag.
You can try with this code snippet.
HTML Snippet
<div id="NameContainer" class="ui-widget">
<div id="Name1">Name1</div>
<div id="Name2">Name2</div>
<div id="Name3">Name3</div>
<div id="Name4">Name4</div>
<br>
<br>
</div>
Javascript Snippet
$(document).ready(function(){
$("#btn").click(function(){
var containerDiv= $("#NameContainer");
var childList = containerDiv.children("div");
var newElementid = childList.length;
var newName = document.createElement("div");
newName.setAttribute("id", "Name"+(newElementid+1));
newName.setAttribute("value", "Name"+(newElementid+1));
newName.setAttribute("class","ui-widget-content");
newName.innerHTML = "Name"+(newElementid+1);
$(childList[childList.length-1]).after(newName);
});
});
This is specific to a situation where there are some elements in the initial list. The same can be modified for dynamic list of implementation by validating that childList.length is != 0 before using the same.

hide all but one element of certain class in Jquery

I am trying to create an effect whereby clicking on a title toggles the corresponding content div. Clicking on another title while some content is showing should hide that content div and show the content div corresponding to the title just clicked.
However the code is not doing anything, as you can see on the following jquery: http://jsfiddle.net/dPsrL/
Any ideas?
HTML:
<div class="row title">
<div class="title" industry_id="education">Ed</div>
<div class="title" industry_id="tech">Tech</div>
<div class="title" industry_id="finance">Fin</div>
</div>
<br>
<br>
<div class="row content">
<div class="content" id="education">Education is great</div>
<div class="content" id="tech">Technology is awesome</div>
<div class="content" id="finance">Finance is super</div>
</div>
JAVASCRIPT:
$(document).ready(function () {
$('.content').hide();
});
('.title').on('click', function () {
var clicked = $(this).attr('industry_id');
alert(clicked);
$("#"+clicked).toggle(400);
$("#"+clicked).siblings().hide();
});
Instead of toggling the clicked element first and then hiding the others, why don't you just hide everything first and then show the clicked one? Saves you a check, and all you have to do is switch the order
$('.title').on('click', function () {
var clicked = $(this).attr('industry_id');
alert(clicked);
$('.content').hide();
$('#' + clicked).show(400);
});
Your attribute doesn't have the id selector in it. You need to do a string concatenation :
$('.title').on('click', function () {
var clicked = $(this).attr('industry_id');
alert(clicked);
$('#' + clicked).toggle(400);
$('#' + clicked).siblings().hide();
//The two last lines could be :
//$('#' + clicked).toggle(400).siblings().hide();
});
Also you have to remove the class content and title on the row since it trigger the click event and the hide part.
Here's a working fiddle : http://jsfiddle.net/dPsrL/3/
Typo on ('.title'). Should be $('.title'). Also, you should probably not give the container divs the same class as the child divs and then use that same class in your CSS and jQuery. It just makes selection more difficult.
jsFiddle example

Replace the same class div and has no ID

I have four DIVS, one is ready and the other three are still hidden. When the link to the second div is pressed, I want the second div to show up, and so for the next link.
The problem is, all the four DIV doesn't have ID and has the same class.
I just want it to automatically run without knowing what is the ID and the class of the div, or anything inside the div. It may look like a slideshow but on click function.
<p> link to the ready div </P>
<p> link to the second div </P>
<p> link to the third div </P>
<p> link to the last div </P>
<div id="wrapper">
<div> this is the div that is ready. This div has no ID and has the same class with others <div>
<div> this is the second div that is hidden. This div has no ID and has the same class with others <div>
<div> this is the third div that is hidden. This div has no ID and has the same class with others <div>
<div> this is the last div that is hidden. This div has no ID and has the same class with others <div>
</div>
FIDDLE
i have made a fiddle that might suite your case please have a look. You can make some modifications according to your needs.
var currentDiv = 0;
$(document).ready(function(){
$(".container div").click(function(){
$(".container div").eq(currentDiv+1).css( "display", "block" );
currentDiv++;
})
});
JSFIddle Link
Im pretty sure this is what you are looking for.
jQuery
$(".options p").click(function () {
var ourPick = $("p").index(this) + 1;
$(".container div:nth-child(" + ourPick + ")").show();
});
Demo Here
So what we are doing is getting the index for the link pressed and then using that to select the div we want to show (this is using :nth-child()).
Note: I have put a container around the links so you it doesn't pick up every p on the page.
If you want only one at a time you can just set them all to hide before showing one.
jQuery:
$(".options p").click(function () {
var ourPick = $("p").index(this) + 1;
$(".container div").hide();
$(".container div:nth-child(" + ourPick + ")").show();
});
Demo Here
JS FIDDLE DEMO
Explanation
<div class="parentDiv">
<div class="div">1</div>
<div class="div">2</div>
<div class="div">3</div>
<div class="div">4</div>
</div>
<div class="buttons">
<a idx="1">1</a>
<a idx="2">2</a>
<a idx="3">3</a>
<a idx="4">4</a>
</div>
$('.buttons a').click(
function(event)
{
var idx = $(event.target).attr('idx');
$('.div').hide(); //Hides all the divs
$('.parentDiv div:nth-child('+idx+')').show(); // Shows required div
}
);
DISADVANTAGE
If you will insert more contents, there is more work. Else no problem..
If you insert a div , you have to change all the links.
<div class="parentDiv">
<div class="div">1</div>
<div class="div">2.0 Inserted Div</div>
<div class="div">2</div>
<div class="div">3</div>
<div class="div">4</div>
</div>
<div class="buttons">
<a idx="1">1</a>
<a idx="2">2.0</a>
<a idx="3">2</a>
<a idx="4">3</a>
<a idx="5">4</a>
</div>
Not here , All the idx has to be changed. Since my code uses nth-child property
Edited
Updated Fiddle
Another Update

Traversing DOM from span in / out of divs

I'm adding a click event to a span that is within a div. The target of this event, which will become visible, is a first div that is within a div, two divs down. How can I traverse the DOM to find it?
Perhaps it'll be clearer with the code:
<div a>
<h2>
<span id="here">Click</span>
</h2>
</div>
<div></div>
<div>
<div class="targetDiv">This is the div we need to find</div>
<div class="targetDiv">There are other divs with the same id, but we don't need to find those</div>
<div class="targetDiv">Not looking for this one </div>
<div class="targetDiv">Or this one either</div>
</div>
I've searched left and right and cannot find an answer. It's important to restrict the event ONLY to the first div immediately after the span.
Any help would be much appreciated.
As shown, the code would look like this:
$('span#here').on('click', function() {
$(this).closest('div').siblings(':contains(.targetDiv)').children().eq(0).show();
}
Here's a sample of the fish we caught
$(function() {
$('#here').on('click', function() {
var div = $(this) //the element clicked
.closest('div') //find nearest parent div
.nextAll(':eq(1)') //find the second next div
.children(':eq(0)') //find the first child of it
.show(); //remove invisible cloak
});
});​
This works. I provided an example you can just save to a html file and test it yourself
<style>
.targetDiv{display:none;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#here').click(function(){
$('.targetDiv').first().show(); // or whatever you want
});
});
</script>
<div a>
<h2>
<span id="here">Click</span>
</h2>
</div>
<div></div>
<div>
<div class="targetDiv">This is the div we need to find</div>
<div class="targetDiv">There are other divs with the same id, but we don't need to find those</div>
<div class="targetDiv">Not looking for this one </div>
<div class="targetDiv">Or this one either</div>
</div>

Categories

Resources