How to append to appended element through JQuery? - javascript

My question is related more to why is this happening, not to knowing how to solve it.
I want to firstly append a <li> to a div and then an <a> to the <li>.
I have the following jQuery code:
$('.patches').empty();
for(i=0;i<patches.length;i++){
$('.patches').append($('<li>', {
id:'li'+ patches[i].name,
class: 'list-group-item'
}));
$('#li'+patches[i].name).append($('<a>',{
href:patches[i].downloadUrl,
text:patches[i].name,
id:'a'+patches[i].name
}));
$('#a'+patches[i].name).append('Version : '+patches[i].version+' Author : '+patches[i].author);
}
The <li> is appended but the <a> isn't, why isn't this working?
EDIT: I have modified the code as follows and it works perfectly:
$('.patches').empty();
for(i=0;i<patches.length;i++){
var listItem=$('<li>', {
id:'li'+ patches[i].name,
class: 'list-group-item'
});
$('.patches').append(listItem);
var aItem=$('<a>',{
href:patches[i].downloadUrl,
text:patches[i].name,
id:'a'+patches[i].name
});
listItem.append(aItem);
listItem.append('<p>Version : '+patches[i].version+' Author : '+patches[i].author+'</p>');
}
This version is almost the same as the previous one, I am just using variables. I would still like to know why the previous version of the code was not working. Could someone explain this?

You are querying DOM before even appending to the DOM.
Append to li directly
for(i=0;i<patches.length;i++){
$('.patches').append($('<li>', {
id:'li'+ patches[i].name,
class: 'list-group-item'
}).append($('<a>',{
href:patches[i].downloadUrl,
text:patches[i].name,
id:'a'+patches[i].name
})));
$('#a'+patches[i].name).append('Version : '+patches[i].version+' Author : '+patches[i].author);
}

You can create a link element and wrap it in a li tag, then append it to the list.
See following please:
$(document).ready(function(){
let patches = [
{name: "test1", downloadUrl: "/url1", version: 1, author: "Alessandro"},
{name: "test2", downloadUrl: "/url2", version: 2, author: "Alessandro"}];
$('.patches').empty();
for(i=0;i<patches.length;i++){
let link = $('<a>',{
href:patches[i].downloadUrl,
text: 'Version : '+patches[i].version+' Author : '+patches[i].author,
id:'a'+patches[i].name
}).wrap("<li></li>").parent();
$('.patches').append($(link, {
id:'li'+ patches[i].name,
class: 'list-group-item'
}));
}
});
$("#btnAdd").click(function(){
$("#atest2").append(";\tSome new information");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAdd">Add something to second element</button>
<ol class="patches"/>
If you want to refer to a specific link element you could use its id, like:
$("#atest2").append(";\tSome new information");
I hope it helps you, bye.

These elements are dynamically created. So, you need to call something like this
$(document).on('event', '.class-name', function(){
// code
});

Modify your logic to first add <a> tag to the <li>, and then add that <li> tag to the <div>...

Related

How to use createElement() in JavaScript?

var htmlComponent = [
{
element : 'button',
text : "Addition"
},
{
element : 'h1',
text : "This is the heading"
},
{
element : 'p',
text : "This is the paragraph."
}
];
htmlComponent.forEach(function(item) {
// Problem here
document.body.appendChild(document.createElement(item.element).appendChild(document.createTextNode(item.text)));
}
Actually I wanted to create an html element using DOM Object but this is not working. I mean my code is not working properly..
but when I changed something Like that:
htmlComponent.forEach(function(item) {
var _element = document.createElement(item.element);
var text = document.createTextNode(item.text);
_element.appendChild(text);
document.body.appendChild(_element);
}
Then the code is working.
Here the main question is why 2nd code is working and the 1st one is not working...... what is the problem in my code.
please Explain me........
You are chaining the calls together like body.createElement().appendChild() where you shouldn't.
This works with createElement() because it returns the element you want to append to, but it doesn't work with appendChild() because that returns the child you just appended, which you are then appending again to the body.
This programming style is known as a "fluent" interface. It is supported by some libraries e.g. jQuery, but not by native Javascript DOM functions.
See https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
Try as follows
appendChild does not return parent
var htmlComponent = [{
element: 'button',
text: "Addition"
},
{
element: 'h1',
text: "This is the heading"
},
{
element: 'p',
text: "This is the paragraph."
}
];
htmlComponent.forEach(function(element) {
var btn = document.createElement(element.element);
var t = document.createTextNode(element.text);
btn.appendChild(t);
document.body.appendChild(btn);
});
According to the documentation for appendChild:
The returned value is the appended child except when the given child
is a DocumentFragment, in which case the empty DocumentFragment is
returned.
You are appending a text node to the button, then trying to append the returned result to the body. This is the reason why you are not seeing the button being appended to the body.
If you break it down like this, it's easier to see what's going on:
document.body.appendChild(
// createElement returns button
document.createElement("button")
// button.appendChild then returns the appended child (a text node)
.appendChild(document.createTextNode("text"))
)

Vue.js - Inconsistencies between model and rendered content

I have the following minimum example:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<ol>
<li v-for="series in currentSeries" v-bind:data-id="series.id">
The ID is <% series.id %>
X
</li>
</ol>
</div>
</body>
<script>
vm = new Vue({
el: '#app',
delimiters: ["<%", "%>"],
data: {
currentSeries: [{id: "1"}, {id: "2"}, {id: "3"}]
},
methods: {
removeSeries: function(id) {
this.currentSeries = this.currentSeries.filter(function(element) {
return element.id != id;
});
}
}
});
$(function() {
$(document).on("click", ".removeSeries", function() {
var id = $(this).parent().data("id");
console.log(id);
vm.removeSeries(id);
});
});
</script>
</html>
I have a list of series in the variable currentSeries. I create a list of these, with adding an -tag to each item to remove it from the list.
If I click on the first 'X', the first element is removed from the list and ID 1 is shown in the console. Then, if I again click on the first element, it should remove the second element (which is now the first one). HOwever, the output id is still 1, i.e. the data-id was not updated of the node during the rendering.
What's the problem here and how to improve on this?
You are mixing jQuery with Vue and both are conceptually different. Here jQuery is entirely unnecessary because you can use Vues built in click event:
// This will call remove series on click and remove the element by the given id
X
Now, this will call your removeSeries for the given id and you can update the underlying model data however you want.
Here's the JSFiddle:
https://jsfiddle.net/vyra5nzc/
Just a note on delimiters, Vue also accepts #{{data}} as a delimiter if you are using the double mustache in some other templating engine such as laravels blade.

Append element AFTER load

I've got this code
$(".test_init").click( function(){
var win = $(this).next(".test_wrap").find(".test_drop");
if ($(win).html().length)
$(win).empty().hide("fast");
else {
$(win).load("URL");
}
});
Which returns me some html form without close button
I wish to add close button using such method without adding it in every-single function
$('*[class*="_drop"]').change(function() {
$(this).append($('<a />', {
class: 'close-drop',
click: function(e) {
e.preventDefault();
alert("test");
}})
);
});
But nothing happens - i can't understand why close button doesn't appends
<div class="test_wrap relative">
<div class="test_drop absolute"></div>
</div>
Example: http://jsfiddle.net/fppfyey7/10/
Your problem is with your CSS, not with your JS. The button is appended but you are hidding it with your style.
For example in this fiddle I append a button with your JS code and your CSS:
Fiddle 1
Now, in this one, I just remove your absolute and relative classes:
Fiddle 2
My solution (isn't good enough, still works)
$('*[class*="_drop"]').ajaxStop(function() {
$(this).prepend('<a onclick="$(this).parent().empty().hide(\'fast\');" class="close-drop"></a>');
});
If here will be better solution, will mark it as answear!

tinyMCE 4: add Class to selected Element

I created a tinymce menu item and what I want it to do is add a class to the selected text element. I cannot seem to figure out how to do this. Any suggestions?
Adding my menu item looks like this:
tinymce.PluginManager.add('button', function(editor, url) {
editor.addMenuItem('button', {
icon: '',
text: 'Button',
onclick: function() {
tinyMCE.activeEditor.dom.addClass(tinyMCE.activeEditor.selection, 'test'); //not working
},
context: 'insert',
prependToContext: true
});
});
I'd be very thankful for any helpful hint.
I found a solution that may not be perfect (for example, if you select part of a text then this doesn't work as I hoped), but for now it does what I want:
tinyMCE.activeEditor.dom.addClass(tinyMCE.activeEditor.selection.getNode(), 'test');
if I do this on a link, for example, the scripts add the classname "test" to my tag.
In order to be able to add a class to the editor you need a dom element in the editor to add the class to. Textnodes may not hold a class.
So i propose you insert a span element with the class you want to add wrapped around the actual selection. Be aware that this won't work if the selection leaps over paragraph boundaries (in this case you will need a bit more complicated code). Try this:
onclick: function() {
var ed = tinyMCE.activeEditor;
var content = ed.selection.getContent({'format':'html'});
var new_selection_content = '<span class="test">' + content + '</span>';
ed.execCommand('insertHTML', false, new_selection_content);
},
this works for me:
setup: function(editor) {
editor.ui.registry.addButton("addClassBtn", {
icon: "insertdatetime",
text: "Highlight ",
onAction: function (_) {
var newContent = "<span class='test'>" + editor.selection.getContent() + "</span>";
editor.selection.setContent(newContent);
}
}
}

How to display the value in html page using dom jquery

I need to display the value in html page using dom jQuery, but its does not display the value. My code:
$(document.createElement("li"))
.append(
$(document.createElement("span"))
.attr({
id: id,
name: name,
value: name
})
)
.addClass('firstli')
)}
span element doesn't have value property, you should use text instead.
var $li = $('<li/>');
$('<span/>', {
id: layer.id,
name: layer.name,
text: layer.name,
'class': 'bullet'
}).appendTo($li)
Try:
$("<li></li>").append(
$("<span></span>").attr({
id: layer.id,
name: layer.name,
}).text(layer.name)
).addClass('bullet').appendTo(document);
And may be you want to append it to document
With your above code you just have created the elements, you still need to add them to the DOM, you have several methods for that, for example you could use .appendTo() to append your elements at the end of some other existent element in the DOM, so your following line:
).addClass('bullet')
would be changed for this one:
).addClass('bullet').appendTo('#someDOMelement');

Categories

Resources