I have a HTML string, I've assigned the div with the class parent an id of myid (in the HTML string). I then append this HTML string to an element with id main. Using the browsers inspect tool I can see that the id has been infact assigned, but for some reason JQuery doesn't know about the newly assigned id.
var html = `
<div class="parent">
<div id="content" >
</div>
<div>`
var newHtml = $(html);
newHtml.find('.parent').attr('id','myid');
$('#main').append(newHtml);
console.log($('.parent').attr('id')); // Logged as undefined.
The method $.fn.find() targets the descendant elements where as $.fn.filter() target the element at same level. As per your HTML .parent is at top level, hence you need to use $.fn.filter() while setting the ID of DIV element.
var html = `<div class="parent">
<div id="content" >
</div>
<div>`
var newHtml = $(html);
newHtml.filter('.parent').attr('id','myid');
$('#main').append(newHtml);
console.log($('.parent').attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="main"></div>
OR, You don't need to use $.fn.find() at all. Just directly use .attr()
var html = `<div class="parent">
<div id="content" >
</div>
<div>`
var newHtml = $(html);
newHtml.attr('id','myid');
$('#main').append(newHtml);
console.log($('.parent').attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="main"></div>
You should use find method in combination with andSelf() method.
andSelf() method add the previous set of elements on the stack to the current set.
Read more here.
var html = `<div class="parent">
<div id="content" >
</div>
<div>`;
var newHtml = $(html);
newHtml.find('.parent').andSelf().attr('id','myid');
$('#main').append(newHtml);
console.log($('.parent').attr('id'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="main"></div>
Related
having a difficult time removing a div inside of a cloned element. run the snippet and notice the do not clone me part gets appended even though it is removed.
let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
clone me
<div class="noClone">
do not clone me
</div>
<button class="clonebtn"> clone it </button>
</div>`
$(document).ready(function() {
let content = $(myhtml);
$('.row').append(content);
$('.row').on('click', '.clonebtn', function() {
let container = $(this).closest('.mycontainer');
let clonedContainer = container.clone();
clonedContainer.remove('.noClone');
$('.row').append(clonedContainer);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
</div>
</div>
or run the fiddle here https://jsfiddle.net/k6jz9xe2/3/
You need to use .find() to find all elements inside the parent div with a class of noClone to remove.
$(selector).remove(anotherselector) in jQuery only removes any elements matching anotherselector from the Array returned by selector. The selector given to the remove() function is only applied to the elements contained in the jQuery collection not to the children of those elements. It is analogous to $(selector).filter(anotherselector).remove().
Consider the following HTML and jQuery code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
Foo
<div id="bar">Bar</div>
</div>
<script>
$('#foo').remove('#bar');
</script>
You may expect that the div with the id "bar" inside the div with the id "foo" will be removed, but this is not the case. Why? The $('#foo') selector returns an Array with just one item: the div with the id of "foo". jQuery attempts to filter through the Array and find an element matching the $('#bar') selector. No element is found and nothing will happen.
The following selector, however, will remove the div with the id of "bar".
$('div').remove('#bar');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
Foo
<div id="bar">Bar</div>
</div>
<script>
$('div').remove('#bar');
</script>
The $('div') selector returns an Array with all the divs on the page. jQuery filters through all of the divs to find an div matching the $('#bar') selector (having an id of "bar"). Having found one, it removes it.
let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
clone me
<div class="noClone">
do not clone me
</div>
<button class="clonebtn"> clone it </button>
</div>`;
$(document).ready(function() {
let content = $(myhtml);
$('.row').append(content);
$('.row').on('click', '.clonebtn', function() {
let container = $(this).closest('.mycontainer');
let clonedContainer = container.clone();
clonedContainer.find('.noClone').remove();
$('.row').append(clonedContainer);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
</div>
</div>
let myhtml = `<div style="border: 1px solid black;" class="mycontainer">
clone me
<div class="noClone">
do not clone me
</div>
<button class="clonebtn"> clone it </button>
</div>`
$(document).ready(function() {
let content = $(myhtml);
$('.row').append(content);
$('.row').on('click', '.clonebtn', function() {
let container = $(this).closest('.mycontainer');
let clonedContainer = container.clone();
clonedContainer.find('.noClone').remove();
$('.row').append(clonedContainer);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
</div>
</div>
similar type of question is already asked link.but my question is bit diffrent.
in my program frequently occur new element with using dom. here my question is
is there any built in function in javascript that i can select last element frequently?
here is an example
var para = document.createElement("div");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
given program append div element frequently and also i want to select div element frequently. similar with a class
thankyou in advance
Use querySelectorAll and pass the class selector. Then target the last element and do whatever
let getAllElem = document.querySelectorAll('.test');
getAllElem[getAllElem.length - 1].classList.add('green')
.green {
color: green
}
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>
<div class="test">5</div>
<div class="test">6</div>
no there is not any built in function in java script but u should try below logic and use it with jquery like $(last_selector(".lastclass")).click(); for select last class and $(last_selector("div")).click(); for elect last element
function last_selector(select){
if(select[0]=="."){
var allSelect = document.getElementsByClassName(select.slice(1));
}
else{
var allSelect = document.getElementsByTagName(select);
}
return allSelect[allSelect.length-1];
}
console.log(last_selector("div"))
console.log(last_selector(".last"))
<div>hello</div>
<div>hello</div>
<div class="last">last class</div>
<div>last element</div>
It will give last span text inside every Div using $(elementName).children("span:last").text()
$(document).ready(function(){
console.log($('div').children("span:last").text())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="time">2016</span><br>
<span class="time">2017</span><br>
<span class="time">2018</span><br>
<span class="time">2019</span><br>
<span class="time">2020</span><br>
<span class="time">2021</span><br>
<span class="time">2022</span><br>
<span class="time">2023</span><br>
<span class="time">2024</span> <br>
</div>
I was wondering how I can do the following.
I would like to set a div containing a certain id with a specific attribute value. Then apply this id to a variable within a function, so that when I call the function it applies the id value.
<html>
<head></head>
<body>
<div id="1123123" value="idloader"> </div>
</body>
</html>
the string that is contained within the id should be set to variable within the function.
<script>
function setTheId() {
div.id.valueOf(id).hasAttribute([value="idloader"])
};
var XYZ = setTheId();
</script>
in conclusion the ( var XYZ = 1123123 ) as set within the DOM element id with attribute value="idloader" should equal to variable within function.
NOTE.. This is not the same as Find an element in DOM based on an attribute value since we are not trying to find an element within the DOM based on attribute but are setting the element with a specific string that can be stored to a variable within the script.
Use querySelectorAll to get all divs that has an id and whose value attribute is equal to "idloader".
var elems = document.querySelectorAll('div[id][value="idloader"]');
for (var i = 0; i < elems.length; i++) {
console.log(elems[i].id);
}
<div id="1123123" value="idloader"> </div>
<div id="1123124" value="idloader"> </div>
<div id="1123125"> </div>
<div value="idloader"> </div>
If you want to get only first div that matches to specifiedĀ CSS selector, use querySelector method:
var MyID = document.querySelector('div[id][value="idloader"]').id;
console.log(MyID);
<div id="1123123" value="idloader"> </div>
<div id="1123124" value="idloader"> </div>
<div id="1123125"> </div>
<div value="idloader"> </div>
Note the value attribute isn't valid for <div> element in accordance to HTML5 Specification. Use data-* Attributes instead.
Yes, it is possible but you don't need to go through all of that to get your desired result.
To get an element with whose attribute equals a specific value, you can use querySelector. Once you have obtained that element, get the id.
var XYZ = document.querySelector('[value="idloader"]').id;
HTML don't admin attrivute value on element div.
The right solution is
let x = document.querySelector('[data-value="idloader"]').id
console.log(x)
<html>
<head></head>
<body>
<div id="1123123" data-value="idloader"> </div>
</body>
</html>
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.
I'm trying to create new elements in another pre-existing <div> element using js DOM.
I'm able to do this if that <div> is called using id but I want to accomplish this by class
This is what I have so far
<html>
<body>
<button onclick="whiskey()">go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p> This is just a control Element</p>
</div>
<script type="text/javascript">
function whiskey(){
var input=document.createElement("input");
input.type="text";a
input.id="sad";
var newdiv=document.createElement("div");
newdiv.appendChild(input);
/* this part doesn't work */
var maindiv=document.getElementsByClassName("pagination-pagination-right");
maindiv.appendChild(newdiv);
}
</script>
</body>
</html>
getElementsByClassName() returns a HTMLCollection which is an array like collection of object, which does not have the appendChild() method. You need to get the first element form the list using an index based lookup then call the appendChild()
function whiskey() {
var input = document.createElement("input");
input.type = "text";
//ID of an element must be unique
input.id = "sad";
var newdiv = document.createElement("div");
newdiv.appendChild(input);
var maindiv = document.getElementsByClassName("pagination-pagination-right");
maindiv[0].appendChild(newdiv);
}
<button onclick="whiskey()">go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p>This is just a control Element</p>
</div>
You could also do this by using jQuery
HTML
<button>go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p> This is just a control Element</p>
</div>
jQuery
$(function(){
$('button').click(function(){
$('<div>A</div>').appendTo('.pagination-pagination-right');
});
});
You can replace $('<div>A</div>') part with whatever element you want to append in your <div>
Fiddle here