Create element in another div element using classname - javascript

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

Related

How to select the inside of jQuery variable

I have some HTML in a jQuery object:
var $div = $(`
<div class="myDiv">
<p class="name"></p>
<p class="data"></p>
</div>`);
I want to change the content of the <p> elements, so I tried like this but in vain:
// Attempt #1
$div.".name".html("name here");
// Attempt #2
$div."> P".html("name here");
How can I use a selector to get the inside of jQuery variable?
Just as you would do when the elements are in the DOM, you need to use find() to retrieve elements within the object. Try this:
var $div = $(`<div class="myDiv">
<p class="name"></p>
<p class="data"></p>
</div>`);
$div.find('p').text('name here');
$div.appendTo('body');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Is there any inbuild function in javascript to select last element with using class selector or element selector?

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>

JQuery unable to find ID assigned to a newly appended HTML string

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>

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.

How to target image inside a div with an id with getelementbyid/tag/name?

Basically I want to change smiley.gif to landscape.jpg without changing divs and tags, but this code is not working.
Any suggestions?
<div id="foo">
<div id="bar"><img src="smiley.gif">
Hello world!
</div>
</div>
<script>
getElementById("bar").getElementsByTagName("img").src="landscape.jpg";
</script>
getElementById is a method that you can only call on the document. getElementsByTagName will return a nodelist, and you need the first element in that nodelist:
document.getElementById("bar").getElementsByTagName("img")[0].src="landscape.jpg";
// Note the `[0]` here -----------------------------------^^^
JSFiddle
it will be better if you assign ID to img tag and use it like this
<div id="foo">
<div id="bar"><img src="smiley.gif" id="myImg"> Hello world! </div>
</div>
<script>
document.getElementById("myImg").src="landscape.jpg";
</script>
jsfiddle1
or Use this
<div id="foo">
<div id="bar"><img src="smiley.gif"> Hello world! </div>
</div>
<script>
var obj = document.getElementById("foo");
if(obj != null)
{
var images = obj.getElementsByTagName('img');
images[0].src = 'landscape.jpg';
}
</script>
As you have confirmed that the layout is fixed, then simply use.
document.getElementById('bar').firstElementChild.src = 'landscape.jpg';
This basically finds the unique element named bar, chooses the first child element (not firstChild, which could be an empty text node) and assigns the new value to src
Documentation on MDN
getElementById
firstElementChild

Categories

Resources