I have been using document.write to generate the HTML part of my page, populating it using a loop. For example I need to create 10 of the following things on my page:
<div class=" normal" id="1"
style="text-align:left;
top: 13px;
left: 5px;
height: 10em;
width: 12em;">
<div class = "wrap">
<div class = "show">
<strong>New York City
<p>Status: Cold</p>
</strong>
</div>
<div class = "noshow">
<P>0001: Normal</P>
</div>
<div class = "here">
<P>0001: online</P>
<P>0002: online</P>
</div>
</div>
</div>
I been doing :
<script>
document.write("<div class=\"");
.. you get the idea</script>
What is another way to do this with jquery or just not-document.write? Could you also provide short example applied onto the code I have above.
Jquery .html() Could be good for this purpose.
<script>
$(function() {
var htmlString = "<div>.. you get the idea</div>";
$("body").html(htmlString);
});
</script>
or this will append html:
.append()
<script>
$(function() {
var htmlString = "<div>.. you get the idea</div>";
$("body").append($(htmlString));
});
</script>
Put the entire thing in a variable :
say : var html_content = "<div class=.....";
and in your loop you can simply use .append(html_content);
You could use DOM manipulation to directly query and add node elements to the DOM.
http://www.howtocreate.co.uk/tutorials/javascript/dombasics
Related
I have a HTML code in variable I want to access the class of that
var test = `
<h2 class= "text">Hello
</h2>`
This is what I try to access the class of attribute and change the color
var query = document.querySelectorAll(".text")
document.getElementById(`${query}`).style.color= red;
I want to access the class of <H2> tag and in change the color.
Have any way to do that?
If you want to modify the string before you add it to the html page.
var test = `
<h2 class= "text">Hello
</h2>`
test = $(test).css("color", "red")
Demo
var test = `
<h2 class= "text">Hello
</h2>`
test = $(test).css("color", "red")
$("body").append(test)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
query is an array, and to get the 1st (only) one, just do query[0].style.color = red;
The reason it's an array is because document.querySelectorAll() returns an array of elements.
But element MUST be in the DOM
Updating my answer now I realise your HTML is in a string. Not sure why you're doing it this way but I digress.
You just include inline styling within your string.
var test = `<html>
<head>
<body>
<h2 style="color: red;" class="text">Hello
</h2>
</body>
</head>
</html>`
I'm trying to find out if it's possible to clone an HTML div with JS, edit it and append it again as a new element. So my source is, for example, this code here:
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC"/>
</div>
</div>
After copying this element, I need to find a way to change the attribute id of the new cloned input, clear the input value and paste it again in the wrapper so that it looks like this at the end:
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC"/>
</div>
<div class="element">
<input id="test--2" value=""/>
</div>
</div>
Does that make sense to you? If yes, how can I get this done? Or is it better to assign the content to a variable to append it? I'm looking for the best way here and maybe my idea is a solution too.
You can use pure JavaScript to do this by just cloning the .element div using the cloneNode() method, assign new id and value to the clone div and finally append it back to the document using the insertBefore() method like this:
let x = document.querySelector(".element");
let y = x.cloneNode(true);
y.children[0].id = "test--2";
y.children[0].defaultValue = "";
x.parentNode.insertBefore(y, x.nextSibling);
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC"/>
</div>
</div>
JSFiddle with the above code: https://jsfiddle.net/AndrewL64/jvc7reza/18/
Based on this answer you could do like:
$('#cloneBtn').on('click', function() {
// get the last input having ID starting with test--
var $inp = $('[id^="test--"]:last'); // Or use :first if you need
// Get parent element
var $div = $inp.closest('.element');
// Create clone
var $div_clone = $div.clone();
// Retrieve number from ID and increment it
var num = parseInt($inp.prop("id").match(/\d+/g), 10) + 1;
// Generate new number and assign to input
$div_clone.find('[id^="test--"]').prop({id: 'test--' + num, value: ''});
// Insert cloned element
$div.after($div_clone); // Or use .before() if you need
});
.element {
padding: 10px;
outline: 2px solid #0bf;
}
<button id="cloneBtn">CLICK TO CLONE</button>
<div class="wrapper">
<div class="element">
<input id="test--1" value="ABC" />
</div>
</div>
Once done inspect the input elements to see the new IDs
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Scrambled elements, retrieve highest ID, increment, clone, append.
If your numbered IDs are scrambled, we first need a way to retrieve the highest ID number. Here's an implementation in pure JavaScript:
function cloneElement () {
const inpAll = document.querySelectorAll('[id^="test--"]');
if (!inpAll.length) return; // do nothing if no elements to clone
const maxID = Math.max.apply(Math, [...inpAll].map(el => +el.id.match(/\d+$/g)[0]));
const incID = maxID + 1;
const element = document.querySelector('.element'); // Get one for cloning
const eleClone = element.cloneNode(true);
const inpClone = eleClone.querySelector('[id^="test--"]');
inpClone.id = 'test--'+ incID;
inpClone.value = incID; // just for test. Use "" instead
document.querySelector('.wrapper').prepend(eleClone);
}
document.querySelector('#cloneBtn').addEventListener('click', cloneElement);
.element {
padding: 10px;
outline: 2px solid #0bf;
}
<button id="cloneBtn">CLICK TO CLONE</button>
<div class="wrapper">
<div class="element">
<input id="test--1" value="1" />
</div>
<div class="element">
<input id="test--23" value="23" />
</div>
<div class="element">
<input id="test--7" value="7" />
</div>
</div>
Once done inspect the input elements to see the new IDs
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
I don't know what data you know, why you want to do such a thing but it can be done :-)
One way is like that:
const elemToCopy = document.getElementById("test--1").parentNode; // I assume you know id
const copiedElem = elemToCopy.cloneNode(true);
const newInput = copiedElem.querySelector("#test--1");
newInput.id = "test--2";
newInput.value = "";
elemToCopy.parentNode.append(copiedElem);
Let me know in a comment if something is not clear :-)
Yes, use jQuery's .clone().
Here is an example that might be relevant to your situation:
let newElement = $('.element').clone();
newElement.find('input').attr('id', 'test--2').val('');
$('.wrapper').append(newElement);
Explanation
In the first line, we created a new cloned element by using jQuery clone().
Then, we found it's child input, changed it's ID and reset the val().
Finally, we found the .wrapper element and appended the new cloned element to it.
I want append an input text in my html page. I use JQuery to do that.
My JQuery script :
$(document).ready(function(){
$(".reply").click(function(){
var tempat=$(this).parent().parent().next(".komentar-balasan");
console.log(tempat[0]);
var html=
tempat[0].append('<input type="text"></input>');
});
});
And the HTML :
<div class="isi">
<div class="like-comment">
<div class="kotak"></div>
<div class="kotak-jumlah">
</div>
<div class="kotak"><button class="reply"></button></div>
</div><div class="komentar-balasan"></div>
The Fiddle
I Don't know why, but instead of displayed the input text box. The browser just display <input type="text"></input>. It's like the browser didn't recognize the HTML code.
It's because tempat[0] is accessing the underlying DOM node rather than the jQuery wrapper. It works fine if you omit the array access and just call append on tempat.
You don't need it here but the right way to get a jQuery wrapped element of a jQuery selector list is to use eq
The problem is that you aren't calling the append element on a jQuery object (which treats strings as HTML), but instead on a native DOM element. The experimental ParentNode#append method treats strings as text, so you are seeing text.
If you omit the [0] before calling append, your code runs perfectly:
$(document).ready(function() {
$("#post-komentar").click(function() {
console.log($(this).siblings('.editor-komentar').val());
});
$(".reply").click(function() {
var tempat = $(this).parent().parent().next(".komentar-balasan");
console.log(tempat[0]);
var html =
tempat.append('<input type="text"></input>');
});
});
.reply {
background-color: #fff;
width: 20px;
height: 20px;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="isi">
<div class="like-comment">
<div class="kotak"><</div>
<div class="kotak-jumlah">
</div>
<div class="kotak"><button class="reply"></button></div>
</div>
<div class="komentar-balasan"></div>
Hello,
Check if this is what you need:
You need to create an element and only then add it.
Here is an example:
$(document).ready(function(){
$(".reply").click(function(){
var tempat=$(this).parent().parent().next(".komentar-balasan");
console.log(tempat[0]);
var newEl = document.createElement('input');
newEl.type = "text";
tempat.append(newEl);
});
});
I hope I have helped!
Remove the [0]. You are dereferencing your jQuery object by doing that.
This works: tempat.append('<input type="text"></input>');
I am trying to apply smiley(emoji) to users comments on a page.
Example all the :) will be applied css attributes replaced with.
Is there a way I can use javascript or jquery to achieve this?
$(":)").css("background-image", "url('smile.gif')");
My Problem is the selector part, Since I dont want to apply the css to the whole div.
you need to wrp you html text ':)' with some html and then you can add css/jq to it. See below javascript code and try to add you css to "smiley" class
document.body.innerHTML = document.body.innerHTML.replace(':)', '');
Below is a possibility. I'm assuming at least that you can discern the comments section from the rest of the webpage.
$("#commentsSection").find(":contains(':)')").each(function() {
$(this).html($(this).html().replace(
':)',
'<span style="background-image: url(\'smile.gif\')" />'
));
});
Since you mentioned that you can't process the comments before submitting to the database, you could hook this code to the $(document).ready() event.
$(document).ready(function() {
$("#btn").click(function() {
$("#commentsSection").find(":contains(':)')").each(function() {
$(this).html($(this).html().replace(
':)',
'<span style="background-image: url(\'smile.gif\')" />'
));
});
});
});
/* Just for visual feedback in the snippet */
#commentsSection span {
display: inline-block;
width: 10px;
height: 10px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someText">
Don't replace this! :)
</div>
<div id="commentsSection">
<h2>
Comments:
</h2>
<div>
Hello! :)
</div>
<div>
Hi!
</div>
<div>
Hello again! :)
</div>
</div>
<button id="btn">
Replace emojis
</button>
Simple example:
<input type="text" id="text"/>
<div id="smiley"></div>
<script>
$(function() {
var text=$('#text').val();
if(text ==":)") {
$("#smiley").append("<img src="smile.gif"/>);
}
})
</script>
I have a a link that looks similar to this
Blog
As you can the link has an ID of 'blog' what I want to do is to create an div on the fly with the ID from the link that was clicked so if the 'blog' is clicked, then the markup would be
<div id="blog">
<!--some content here-->
</div>
Like wise if for instance the news link is clicked then I would like,
<div id="news">
<!--some content here-->
</div>
to be created in the markup if this possible? and how Im pretty new to jQuery.
Try this:
$("a").click(function(){
$("#wrapper").append("<div id=" + this.id + "></div>");
});
Not tested, should work ;)
where: #wrapper is parent element, work on all a as you see.
You will need to give the div a different ID. Perhaps you could give it a class instead:
$("#blog").click(function() {
$(this).after("<div class='blog'>...</div>");
return false;
});
That's just one of many ways to create a div. You probably also want to avoid duplicates however in which case, use something like this:
$("#blog").click(function() {
var content = $("#blog_content");
if (content.length == 0) {
content = $("<div></div>").attr("id", "blog_content");
$(this).after(content);
}
content.html("...");
return false;
});
As for how to handle multiple such links I would do something like this:
Blog
News
Weather
<div id="content"></div>
with:
$("a.content").click(function() {
$("#content").load('/content/' + this.id, function() {
$(this).fadeIn();
});
return false;
});
The point is this one event handler handles all the links. It's done cleanly with classes for the selector and IDs to identify them and it avoids too much DOOM manipulation. If you want each of these things in a separate <div> I would statically create each of them rather than creating them dynamically. Hide them if you don't need to see them.
Try This :
<a id="blog">Blog</a>
<a id="news">news</a>
<a id="test1">test1</a>
<a id="test2">test2</a>
$('a').click(function()
{
$('<div/>',{
id : this.id,
text : "you have clicked on : " + this.id
}).appendTo("#" + this.id);
});
First of all you should not make 2 elements with same ID. At your example a and div will both have id="blog". Not XHTML compliant, plus might mess up you JS code if u refernce them.
Here comes non-jquery solution (add this within script tags):
function addDiv (linkElement) {
var div = document.createElement('div');
div.id = linkElement.id;
div.innerHTML = '<!--some content here-->';
document.body.appendChild(div); // adds element to body
}
Then add to HTML element an "event handler":
Blog
This question describes how to create a div. However, you shouldn't have two elements with same IDs. Is there any reason why you can't give it an id like content_blog, or content_news?
Unfortunately if you click on a link the page you go to has no idea what the idea of the link you clicked was. The only information it knows is what's contained in the URL. A better way to do this would be to use the querystring:
Blog
Then using the jQuery querystring plugin you could create the div like:
$("wrapper").add("div").attr("id", $.query.get("id"));
You shouldn't have elements in your page with the same ID. Use a prefix if you like, or perhaps a class.
However, the answer is as follows. I am imagining that your clickable links are within a div with the ID "menu", and your on-the-fly divs are to be created within a div with the ID "content".
$('div#menu a').click(function(){
$('div#content').append('<div id="content_'+this.id+'"><!-- some content here --></div>');
});
Any problems, ask in the comments!
Also the following statement is available to create a div dynamically.
$("<div>Hello</div>").appendTo('.appendTo');
Working fiddle: https://jsfiddle.net/andreitodorut/xbym0bsu/
you can try this code
$('body').on('click', '#btn', function() {
$($('<div>').text('NewDive').appendTo("#old")).fadeOut(0).fadeIn(1000);
})
#old > div{
width: 100px;
background: gray;
color: white;
height: 20px;
font: 12px;
padding-left: 4px;
line-height: 20px;
margin: 3px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div>
<!-- Button trigger modal -->
<button type="button" id="btn">Create Div</button>
<div id="old">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>