I have a dynamically created html elements under a for loop in JavaScript, these dynamic elements also has a dynamic id, my question is how can I hide the dynamically created elelment with a dynamic id. Thank you.
This is my code so far. I want to target the dynamic id and hide it.
product_list += '<div class="plProductContainer hide" data-pids="' + a_data.products[i].pid + '" id="'+a_data.products[i].pid+'">';
It has a dynamic id.
I would recommend you will use classes instead of id, but for this example you could use something like this. hide the element using a class.
$(document).ready(function(){
$(function(){
$(".add-more").on("click", function(){
var list = $(".list");
var random_id = Math.floor(Math.random() * (99999 - 1 + 1)) + 1;
var child = document.createElement("li");
var text = document.createTextNode("Lorem Ipsum");
child.setAttribute("id", random_id);
child.appendChild(text);
list.append(child);
});
});
$(function(){
$(".list").on("click", "li", function(){
var id = $(this).attr("id");
$("#" + id).addClass("hidden");
console.log("This id: " + id + " is hidden");
});
});
});
a{
color: blue;
cursor: pointer;
}
ul{
margin-top: 20px;
padding: 0;
}
li{
list-style: none;
cursor: pointer;
}
li:hover{
color: red;
}
li + li{
margin-top: 20px;
}
li.hidden{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div>
<a class="add-more">Click me!</a>
</div>
<ul class="list">
<li id="0">Lorem Ipsum</li>
</ul>
document.getElementById(a_data.products[i].pid).style.display = 'none';
Let me assume that you are using jquery. Try something like this:
$(".plProductContainer.hide").hide();
or
var elementId = $(".plProductContainer.hide").attr("id");
$("#"+elementId).hide();
or
If your element is inside another element with id someId, then:
$("#"+someId).children()[i].hide(); //i is the loop counter that you have used to create element dynamically
or
$("#"+a_data.products[i].pid).hide(); //i is the loop counter that you have used to create element dynamically
It becomes easier if you already know the values of you loop counter i.e value of i, if you don't know that then you can also use selectors like nth child. Let me know if any of the above works, else I'll put up more selectors.
Related
Maybe I'm way off, but here we go.
print '<li '.$class.'><a id="flodet" href="index.php?artikelid='.$rad["id"].'">'.$rad["header"].'</a> </li>';
This line print links to articles from a database. The class flodet just style the link. What I want to do is to create another div inside the class flodet. I have tried to do this with these couple of lines of javascript.
function myFunc() {
var bild = document.createElement("div");
document.getElementById('flodet').appendChild(bild);
}
Am I way off or am I on the right track?
Here is a snippet to play around with.
Few suggestions:
'<li '.$class.'> - this seems to be wrong ; use the attribute class
You could select the li using ul > li if needed and can avoid setting class to each li; You could even decorate the parent ul with a class and select the li's using ul.myList li where myList is the class of ul
function myFunc() {
/* To add a 'div' inside the list item anchor */
/*
var bild = document.createElement("div");
bild.innerHTML = "My new DIV";
document.getElementById('flodet').appendChild(bild);
*/
/* To add a 'div' inside each list item */
var listItems = document.querySelectorAll("ul > li");
for (var i = 0; i < listItems.length; i++) {
var bild = document.createElement("div");
bild.innerHTML = "My Div" + i;
/* Add an attribute, say 'class' */
bild.setAttribute("class", "divClass");
listItems[i].appendChild(bild);
}
}
window.onload = myFunc;
/* To select the list items */
ul > li {
color: #DDD;
}
.divClass {
border: 1px solid #F2F2F2;
}
<ul>
<li>
<a id="flodet" href="">Link 1</a>
</li>
<li>
<a id="flodet2" href="">Link 2</a>
</li>
<li>
<a id="flodet3" href="">Link 3</a>
</li>
</ul>
You are most likely on the right track, but let me suggest one thing about your tiny code-piece:
I you are using styles to brush up the link, you are better of to set the class-attribute on the link rather than the id. ID's should be unique - That might not be the case, if there are more elements of this type generated by your code.
document.getElementById('flodet').insertAdjacentHTML("beforeend", "<div class='inline'> World!</div>");
.inline {
display: inline-block;
}
<div id="flodet">Hello </div>
looks okay, add it inside a document.ready or something simular and you should be good to go.
I would suggest one change though,
Instead of
var bild = document.createElement("div");
document.getElementById('flodet').appendChild(bild);
i would just do
document.getElementById('flodet').insertAdjacentHTML("beforeend", "<div>Hello World!</div>");
Fiddle here: http://jsfiddle.net/yv1vLhd9/
For whatever reasons, suppose I want to replace three dom elements with three others using JQuery, but I want to transfer one or more data attributes from the first elements onto their corresponding replacements.
Given the following HTML:
<div class='original' data-custom="dog"></div>
<div class='original' data-custom="cat"></div>
<div class='original' data-custom="sheep"></div>
And the following CSS:
div {
width: 100px;
height: 100px;
}
div:before {
content: attr(data-custom);
}
.original {
border: blue solid 1px;
}
.new {
border: pink solid 1px;
}
How can I make sure there is a new element with each of the custom data attributes?
For example:
$(document).ready( function(){
var $originalEl = $('.original')
var originalData = $originalEl.data('custom')
var replacement = '<div class="new" data-custom="' + originalData + '"></div>'
$originalEl.after(replacement).hide()
});
But this creates three new data-custom="dog" attributes.
You must use $.each for the element.
Starting after you declare $originalEl
$originalEl.each(function(){
// code here
})
Here is your code updated http://jsfiddle.net/yv1vLhd9/4/
http://jsfiddle.net/VixedS/wz95hh3r/1/
$(document).ready(function(){
$('.original').each(function(){
$(this).hide().clone().attr('class','new').show().appendTo('body');
})
});
jQuery provides a host of DOM manipulation methods that will help you achieve the desired input. As noted by some of the other answers, you'll need to traverse over the set of matched elements using $.each. In addition, rather than creating new elements from strings, you can use the .clone() method to:
clone the existing element
modify your new element
insert it after the original element
traverse to the original element
and finally hide the original element.
$(function () {
$('.original').each(function (idx, elem) {
$(elem)
.clone()
.removeClass('original')
.addClass('new')
.insertAfter($(elem))
.prev()
.hide();
});
});
div {
width: 100px;
height: 100px;
}
div:before {
content: attr(data-custom);
}
.original {
border: blue solid 1px;
}
.new {
border: pink solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='original' data-custom="dog"></div>
<div class='original' data-custom="cat"></div>
<div class='original' data-custom="sheep"></div>
API Method References:
jQuery.each()
.clone()
.removeClass()
.addClass()
.insertAfter()
.prev()
.hide()
I have a simple html (see here: http://plnkr.co/edit/nqfLNfYxV2B8AwsDAcNu?p=preview):
<section class="divs">
<div>div1
<div>div1.1.
<div>div1.1.1</div>
<div>div1.1.2</div>
</div>
<div>div1.2.</div>
</div>
<div>div2</div>
</section>
I want go through all section div:first-child elements and add some mark to see if it belongs to that selector. In order to implement this there is following code:
$(function(){
$('section div:first-child').each(function(index,element){
console.log('element.html before: '+$(element).html());
var elementHTML = '['+index+']: '+$(element).html();
$(element).html(elementHTML);
console.log('element.html after: '+$(element).html());
});
});
But it adds the [index] to the element's html only for the first selector.
Can anybody explain why?
UPD
Not quite the answer, but nevertheless, Pete gave me the understanding of the problem.
So in order to make it working there is necessary to change
$(element).html(elementHTML);
to
$('section div:first-child')
.eq(index).html(elementHTML);
It's not about efficiency ofcourse, it's about how to solve the problem in place. The real solution, no doubt, is to use .prepend() method.
Your problem is the first time instance of section div:first-child is the top level div (div1) so when you replace the html of this div, the divs 2 and 3 in the loop no longer exist in the dom and so they don't get updated as such
Instead of replacing the html, just prepend the text:
$('section div:first-child').each(function(index, element) {
$(element).prepend('[' + index + ']: ');
});
New plunker
$('section div:first-child')
https://developer.mozilla.org/en-US/docs/Web/CSS/%3Afirst-child
The :first-child CSS pseudo-class represents any element that is the
first child element of its parent.
If you want to select only the divs one level below section, you can try:
$('section > div')
Since you replace the HTML every time, the elements are replaced on the fly. To avoid that, don't replace the entire HTML, just $.prepend() to it. Try it:
$(function() {
$('section div:first-child').each(function(index, element) {
console.log('element.html before: ' + $(element).html());
var elementHTML = '[' + index + ']: ';
$(element).prepend(elementHTML); // <------------------------ HERE !
console.log('element.html after: ' + $(element).html());
});
});
body * { box-sizing: border-box; }
div { background-color: white; }
section div { border: solid 2px #888; margin: 4px; padding: 10px; }
section div:first-child { background-color: lightcyan; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<section class="divs">
<div>div1
<div>div1.1.
<div>div1.1.1</div>
<div>div1.1.2</div>
</div>
<div>div1.2.</div>
</div>
<div>div2</div>
</section>
When you set the html, the elements below it don't get updated, they get replaced
Your code works, it's just updating the elements that are no longer attached to the DOM.
I have 100 DIVS in an array called 'lights', appended to the page with a unique ID. Some of those DIVS are also in another array called 'frozen'.
How can I change the background color of the DIVS in 'lights' but not the divs in the 'frozen' array?
For example, to change all of the divs I would use:
for(var l=0;l<LIGHTS_NUMOF;l++){
$("#light"+l).css("background-color", "#ff0000");
}
Generating the array:
var LIGHTS_NUMOF = 100;
var lights = [];
for(var l=0;l<LIGHTS_NUMOF;l++){
var newLight = $("<div class=\"light\" id=\"light"+l+"\"></div>");
$(".lights").append(newLight);
lights.push(newLight);
}
However, this obviously changes ALL of the divs.
How do I avoid changing the DIVS which are in the 'frozen' array?
Ideally I would like to express lights.backgroundcolor = 'red' where DIV isn't 'frozen'.
Adding DIV to 'frozen':
$( ".light" ).click(function() {
frozen.push(this);
});
If you are actually looking at items in the DOM, you can easily do what you want using jQuery.not() like the following example.
$(document).ready(function() {
$("#changeLights").on("click", function() {
$(".lights").not(".frozen").addClass("frozen");
});
});
div {
height : 50px;
width : 50px;
background-color : #CCC;
margin: 5px;
float: left;
}
.frozen {
background-color : #F00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="lights"></div>
<div class="lights"></div>
<div class="lights frozen"></div>
<div class="lights"></div>
<div class="lights frozen"></div>
<div class="lights frozen"></div>
<input id="changeLights" type="button" value="Change" />
Try this:
for(var l=0;l<LIGHTS_NUMOF;l++){
if(frozenArray.indexOf(lightsArray[l]) == -1){ // if id is not in frozen array
$("#light"+l).css("background-color", "#ff0000");
}
}
First of all...
Try modify this part of your code
$(".light").click(function() {
$(this).addClass("frozen");
});
Then to get all of that is not frozen, do this:
$(".light").not(".frozen").css("background-color", "#ff0000");
So I wrote this to take a button and recreate it as an Link with spans inside. However, I cant seem to get this to work for multiple buttons. I end up needing to copy and past the JS and enter in the different classes duplicating the entire script. There has to be an easier way to do this... Any thoughts?
Example of two buttons, and the only working solution thus far...
http://jsfiddle.net/En72J/5/
HTML
<div class="DIV_ONE">
<input type="button" class="INPUT_ONE" value="Today's Work Items 10" onclick="hAction_win1(document.win1,'CU_APPL_SUM_WRK_PERFORM_WEEKS', 0, 0, 'This Week\'s Items 10', false, true);" tabindex="16" name="CU_APPL_SUM_WRK_DATE_SEL_DAYS">
</div>
JQuery
// Page First loads Input Button Wrapped in Div.
// Grab Input Buttons Numbers ( Last 2 Characters )
var number = $('.INPUT_ONE').val().substr(-2);
// Grab Input Buttons Text, Minus the Numbers.
var term = $('.INPUT_ONE').val().slice(0, -2);
// Grab Input Buttons OnClick Value
var script = $('.INPUT_ONE').attr("onclick");
// Append 'term' Float Left
$('.DIV_ONE').append('<span class="text">' + term + '</span>');
// Append 'number' Float Right
$('.DIV_ONE').append('<span class="number">' + number + '</span>');
// Wrap Both 'term' and 'number' in an <A> LINK and set OnClick with 'script' var.
var second = $('.DIV_ONE').wrapInner('');
// Finally, Delete old Button. New <A> Link as Victor!
$('.INPUT_ONE').remove();
CSS
.btn_style {
border-bottom: 1px dotted #CCCCCC;
color: #666666;
display: block;
font-family: verdana;
font-size: 12px;
overflow: auto;
text-decoration: none;
}
.number {
background: none repeat scroll 0 0 #72716E;
color: #FFFFFF;
display: block;
float: right;
font-weight: bold;
padding: 4px;
position: relative;
width: 20px;
}
.text {
float: left;
padding: 4px;
}
Consider using a second class name to identify the elements you wish to process, then loop through them like so:
<div class="DIV_ONE buttonMe">
<input type="button" class="INPUT_ONE" value="Today's Work Items 10" onclick="hAction_win1(document.win1,'CU_APPL_SUM_WRK_PERFORM_WEEKS', 0, 0, 'This Week\'s Items 10', false, true);" tabindex="16" name="CU_APPL_SUM_WRK_DATE_SEL_DAYS">
</div>
JS:
$('.buttonMe').each(function() {
current= $(this);
// at this point "current" points to the outer DIV
currentInput = $(this).find('input')
// then you can manipulate the current input
})
Then you can treat "currentInput" as if it were the hard-coded element reference you're currently using in your code.
A simple loop would solve that :
$('input[class^="INPUT_"]').each(function() {
var n = $('<span />', {'class':'number', text : this.value.slice(-2)}),
t = $('<span />', {'class':'text', text : this.value.slice(0,-2)}),
a = $('<a />', {'class':'btn_style', onclick : $(this).attr('onclick')});
$(this).closest('div').append(a.append(n,t)).end().remove();
});
FIDDLE
You could select all inputs of type button by using
$('input:button').each( function(index) {
//do work here
});
and go through each button on your page.
create a seperate function and call the function with a selector for any number of inputs and div
function createlink(input, div) {
// Page First loads Input Button Wrapped in Div.
// Grab Input Buttons Numbers ( Last 2 Characters )
var number = $(input).val().substr(-2);
// Grab Input Buttons Text, Minus the Numbers.
var term = $(input).val().slice(0, -2);
// Grab Input Buttons OnClick Value
var script = $(input).attr("onclick");
// Append 'term' Float Left
$(div).append('<span class="text">' + term + '</span>');
// Append 'number' Float Right
$(div).append('<span class="number">' + number + '</span>');
// Wrap Both 'term' and 'number' in an <A> LINK and set OnClick with 'script' var.
var second = $(div).wrapInner('');
// Finally, Delete old Button. New <A> Link as Victor!
$(input).remove();
}
createlink('.INPUT_ONE', '.DIV_ONE');
createlink('.INPUT_TWO', '.DIV_TWO');
fiddle here
Use JQuery's $(this) and JQuery's .each.
Here's a working fiddle: http://jsfiddle.net/4jqBj/
HTML:
<div class="item">
<input type="button" class="item_btn" value="Today's Work Items 10" tabindex="16" />
</div>
<div class="item">
<input type="button" class="item_btn" value="This Week's Items 22" tabindex="16" />
</div>
JQUERY:
$(".item_btn").each(function () {
var number = $(this).val().substr(-2);
var term = $(this).val().slice(0, -2);
$(this).parent().append('<span class="text">' + term + '</span>').append('<span class="number">' + number + '</span>');
$(this).parent().wrapInner('');
$(this).remove();
});